你如何为 getInitialProps 编写 Jest 测试?

How do you write Jest tests for getInitialProps?

static async getInitialProps({ query }) {
  let content;
  let alert;

  try {
    const first = query.first ? query.first : '';
    content = await getContent(first);
  } catch (error) {
    alert = 'There was an error loading data, please try again.';
    content = [];
  }

  return {
    content,
    alert,
  };
}

我正在尝试为此逻辑编写测试,但因为它是服务器端代码,所以我很难理解如何为其编写测试,因为它在 instance() 中不可用。

Google 没有向我展示这方面的方法,所以我想知道其他人是如何处理 getInitial 道具的编写测试的。

首先,看看 static method and what does the static keyword 做什么。

由于 getInitialProps 只是组件上的静态函数,您可以像任何其他函数一样手动测试它。

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."
    });
  });
});

大部分时间,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 }
  }

documentation describes getInitialProps goal 并且我们可以确认直接调用它并测试它的 return 值作为 Object.

是可以的

Notice that to load data when the page loads, we use getInitialProps which is an async static method. It can asynchronously fetch anything that resolves to a JavaScript plain Object, which populates props.

Data returned from getInitialProps is serialized when server rendering, similar to a JSON.stringify. Make sure the returned object from getInitialProps is a plain Object and not using Date, Map or Set.

For the initial page load, getInitialProps will execute on the server only. getInitialProps will only be executed on the client when navigating to a different route via the Link component or using the routing APIs.