简体   繁体   English

你如何为 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,
  };
}

I'm trying to write tests for this logic but because it is server side code I'm struggling to understand how I write a test for it as it isn't available to me in instance().我正在尝试为此逻辑编写测试,但是因为它是服务器端代码,所以我很难理解我是如何为它编写测试的,因为它在 instance() 中对我不可用。

Google hasn't shown me the way on this one so I'm wondering how others have tackled writing tests for getInitial props.谷歌没有向我展示这个方法,所以我想知道其他人是如何处理为 getInitial 道具编写测试的。

First, take a look at what's a static method and what does the static keyword do.首先,看看什么是static 方法以及static关键字的作用。

Since getInitialProps is just a static function on a component , you can test it manually like any other function.由于getInitialProps只是组件上的 static function ,因此您可以像任何其他 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 .大多数时候, 无论如何都会这样调用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 } }

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 . 文档描述了getInitialProps目标,我们可以确认直接调用它并测试它的返回值作为Object是可以的。

Notice that to load data when the page loads, we use getInitialProps which is an async static method.请注意,要在页面加载时加载数据,我们使用getInitialProps这是一个async static 方法。 It can asynchronously fetch anything that resolves to a JavaScript plain Object , which populates props .它可以异步获取任何解析为 JavaScript 普通Object的东西,它填充props

Data returned from getInitialProps is serialized when server rendering, similar to a JSON.stringify .getInitialProps返回的数据在服务器渲染时被序列化,类似于JSON.stringify Make sure the returned object from getInitialProps is a plain Object and not using Date , Map or Set .确保从getInitialProps返回的 object 是普通的Object并且不使用DateMapSet

For the initial page load, getInitialProps will execute on the server only.对于初始页面加载, getInitialProps将仅在服务器上执行。 getInitialProps will only be executed on the client when navigating to a different route via the Link component or using the routing APIs. getInitialProps只会在通过Link组件导航到不同的路由或使用路由 API 时在客户端上执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM