Max*_*ynn 9 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,
};
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试为这个逻辑编写测试,但因为它是服务器端代码,我很难理解我如何为它编写测试,因为它在 instance() 中对我不可用。
谷歌没有向我展示这个方法,所以我想知道其他人是如何解决为 getInitial props 编写测试的。
首先,看看什么是静态方法以及static
关键字的作用。
由于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."
});
});
});
Run Code Online (Sandbox Code Playgroud)
大多数时候,getInitialProps
无论如何都这样称呼。
Run Code Online (Sandbox Code Playgroud)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
静态方法。它可以异步获取解析为 JavaScript 纯文本的任何内容Object
,并填充props
.返回的数据
getInitialProps
在服务器渲染时被序列化,类似于JSON.stringify
. 确保 from 返回的对象getInitialProps
是普通对象Object
并且不使用Date
,Map
或Set
。对于初始页面加载,
getInitialProps
将仅在服务器上执行。getInitialProps
只有在通过Link
组件导航到不同的路由或使用路由 API时,才会在客户端上执行。
归档时间: |
|
查看次数: |
3758 次 |
最近记录: |