簡體   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,
  };
}

我正在嘗試為此邏輯編寫測試,但是因為它是服務器端代碼,所以我很難理解我是如何為它編寫測試的,因為它在 instance() 中對我不可用。

谷歌沒有向我展示這個方法,所以我想知道其他人是如何處理為 getInitial 道具編寫測試的。

首先,看看什么是static 方法以及static關鍵字的作用。

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

大多數時候, 無論如何都會這樣調用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 } }

文檔描述了getInitialProps目標,我們可以確認直接調用它並測試它的返回值作為Object是可以的。

請注意,要在頁面加載時加載數據,我們使用getInitialProps這是一個async static 方法。 它可以異步獲取任何解析為 JavaScript 普通Object的東西,它填充props

getInitialProps返回的數據在服務器渲染時被序列化,類似於JSON.stringify 確保從getInitialProps返回的 object 是普通的Object並且不使用DateMapSet

對於初始頁面加載, getInitialProps將僅在服務器上執行。 getInitialProps只會在通過Link組件導航到不同的路由或使用路由 API 時在客戶端上執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM