How do you write Jest tests for getInitialProps? How do you write Jest tests for getInitialProps? reactjs reactjs

How do you write Jest tests for getInitialProps?


First, take a look at what's a static method and what does the static keyword do.

Since getInitialProps is just a static function on a component, you can test it manually like any other function.

import MyComponent from "./path/to/MyComponent";// Mock the getContent function which I don't know where it comes from.jest.mock("../someModule.js", () => ({  getContent: () => Promise.reject()}));describe("MyComponent", () => {  it('populates the "alert" prop on getContent failure.', async () => {    // Inject anything you want to test    const props = await MyComponent.getInitialProps({      query: { first: "whatever" }    });    // And make sure it results in what you want.    expect(props).toEqual({      content: [],      alert: "There was an error loading data, please try again."    });  });});

Most of the time, getInitialProps is called like that anyway.

export default class MyApp extends App {  static async getInitialProps ({ Component, router, ctx }) {    let pageProps = {}    if (Component.getInitialProps) {      pageProps = await Component.getInitialProps(ctx)    }    return { pageProps }  }

The documentation describes getInitialProps goal and we can confirm that it's ok to call it directly and test its return value as an Object.

Notice that to load data when the page loads, we use getInitialPropswhich is an async static method. It can asynchronously fetchanything that resolves to a JavaScript plain Object, which populatesprops.

Data returned from getInitialProps is serialized when serverrendering, similar to a JSON.stringify. Make sure the returnedobject from getInitialProps is a plain Object and not usingDate, Map or Set.

For the initial page load, getInitialProps will execute on theserver only. getInitialProps will only be executed on the clientwhen navigating to a different route via the Link component or usingthe routing APIs.