gpt4 book ai didi

javascript - 你如何为 getInitialProps 编写 Jest 测试?

转载 作者:行者123 更新时间:2023-11-30 10:59:31 24 4
gpt4 key购买 nike

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 Prop 的编写测试的。

最佳答案

首先,看一下什么是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

Notice that to load data when the page loads, we use getInitialPropswhich is an async static method. It can asynchronously fetchanything that resolves to a JavaScript plain Object, which populatesprops.

Data returned from getInitialProps is serialized when serverrendering, similar to a JSON.stringify. Make sure the returnedobject from getInitialProps is a plain Object and not usingDate, Map or Set.

For the initial page load, getInitialProps will execute on theserver only. getInitialProps will only be executed on the clientwhen navigating to a different route via the Link component or usingthe routing APIs.

关于javascript - 你如何为 getInitialProps 编写 Jest 测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58490318/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com