【问题标题】:How do you write Jest tests for getInitialProps?你如何为 getInitialProps 编写 Jest 测试?
【发布时间】:2020-02-17 18:43:50
【问题描述】:
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 道具编写测试的。

【问题讨论】:

    标签: javascript reactjs jestjs next.js


    【解决方案1】:

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

    请注意,在页面加载时加载数据,我们使用getInitialProps 这是一个async 静态方法。它可以异步获取 任何解析为 JavaScript 普通 Object 的东西,它填充 props.

    getInitialProps返回的数据在服务端被序列化 渲染,类似于JSON.stringify。确保退回的 来自getInitialProps 的对象是一个普通的Object 并且没有使用 DateMapSet

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

    【讨论】:

    • 谢谢,这是一个很好的解释。我试图从实例中获取它,但没有意识到我可以直接从组件中获取它
    • 感谢您链接到文档——我在这里提交了一些链接更新。我也喜欢检查具有适当属性的道具。这让我可以快速捕捉动态 CMS 拼写错误,例如`expect(testProps).toHaveProperty('props.footerProps');`.
    猜你喜欢
    • 2022-01-23
    • 2016-01-19
    • 2020-10-12
    • 2019-05-26
    • 2020-03-26
    • 1970-01-01
    • 2021-12-03
    • 2015-03-30
    • 1970-01-01
    相关资源
    最近更新 更多