您如何为getInitialProps编写Jest测试?

时间:2019-10-21 16:18:12

标签: 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,
  };
}

我正在尝试为此逻辑编写测试,但是由于它是服务器端代码,因此我难以理解如何为它编写测试,因为在instance()中我无法使用它。

Google尚未向我展示这方面的方法,所以我想知道其他人如何解决针对getInitial道具编写测试的问题。

1 个答案:

答案 0 :(得分:3)

首先,看看什么是static methodstatic 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,我们可以确认可以直接调用它并以Object测试其返回值。

  

请注意,要在页面加载时加载数据,我们使用getInitialProps   这是async静态方法。它可以异步获取   解析为JavaScript纯Object的所有内容   props

     

getInitialProps返回的数据在服务器时被序列化   渲染,类似于JSON.stringify。确保退货   getInitialProps中的对象是普通的Object,未使用   DateMapSet

     

对于初始页面加载,getInitialProps将在   仅服务器。 getInitialProps仅在客户端上执行   通过Link组件或使用导航到其他路线时   路由API。

相关问题