你如何为 getInitialProps 编写 Jest 测试?

Max*_*ynn 9 javascript reactjs jestjs next.js

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,
  };
}
Run Code Online (Sandbox Code Playgroud)

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

谷歌没有向我展示这个方法,所以我想知道其他人是如何解决为 getInitial props 编写测试的。

Emi*_*ron 8

首先,看看什么是静态方法以及static关键字的作用。

由于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."
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

大多数时候,getInitialProps无论如何都这样称呼

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

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx)
    }

    return { pageProps }
  }
Run Code Online (Sandbox Code Playgroud)

文档描述getInitialProps的目标,我们可以证实,它的确定直接调用它,并测试它的返回值作为Object

请注意,要在页面加载时加载数据,我们使用的getInitialPropsasync静态方法。它可以异步获取解析为 JavaScript 纯文本的任何内容Object,并填充 props.

返回的数据getInitialProps在服务器渲染时被序列化,类似于JSON.stringify. 确保 from 返回的对象getInitialProps是普通对象Object并且不使用 Date,MapSet

对于初始页面加载,getInitialProps将仅在服务器上执行。getInitialProps只有在通过Link组件导航到不同的路由或使用路由 API时,才会在客户端上执行。