我希望有不同的单元测试来测试我的组件的不同状态,以及它与异步请求的交互。我在做这件事上有很多困难。大多数文档都说要“模拟”触发异步状态更改的事件(即模拟组件的单击),然而,我的状态应该在组件加载时更改,而不是通过任何用户交互来更改。我看过对act函数(https://reactjs.org/blog/2019/02/06/react-v16.8.0.html#testing-hooks)的引用,但我不知道如何在此上下文中实现它。
下面是我的功能react组件:
import { useRequest } from '@umijs/hooks' // Request custom hook
// An async function that does an async task to get data
async function someAsyncFunctionToFetch() => {
return Promise.resolve({data: 'data'})
}
// The functional component
export function TestComponent() {
const { data, error, loading } = useRequest(FulfillmentService.getFullfillmentServices)
const loadingMarkup = (
<p>Loading</p>
)
const errorMarkup = (
<p>Error</p>
)
const contentMarkup = (
<p>{ data }</p>
)
if (loading) {
return loadingMarkup
} else if (error) {
return errorMarkup
} else if (!isEmpty(data)) {
return contentMarkup
} else {
return <p>Some empty state</p>
}
}以下是我想要实现的测试:
describe('TestComponent', () => {
it.todo('when data is loading the loading markup should be rendered')
it.todo('when data fetching results in an error the error markup should be rendered')
it.todo('when data fetching returns with valid data the content markup should be rendered')
it.todo('when data fetching returns an empty data object the empty state markup should be rendered')
})发布于 2020-04-12 01:44:13
要测试组件为每个状态呈现所需的标记,您可以模拟useRequest挂钩的返回值。这可以通过使用jest.mock函数模拟@umijs/hooks模块的行为来实现:
import { useRequest } from "@umijs/hooks";
jest.mock("@umijs/hooks");现在可以使用mockReturnValue函数模拟每个状态。例如,要模拟加载状态,我们可以这样做:
useRequest.mockReturnValue({
loading: true
});每个场景的测试看起来都是这样的:
import { useRequest } from "@umijs/hooks";
jest.mock("@umijs/hooks");
describe("TestComponent", () => {
describe("loading description", () => {
beforeEach(() => useRequest.mockReturnValue({ loading: true }));
it("loading assertion", () => {/* ... */});
});
describe("error description", () => {
beforeEach(() => useRequest.mockReturnValue({ error: "Given error" }));
it("error assertion", () => {/* ... */});
});
describe("valid data description", () => {
beforeEach(() => {
useRequest.mockReturnValue({ data: { value: "Given data" }});
});
it("valid data assertion", () => {/* ... */});
});
describe("empty data description", () => {
beforeEach(() => useRequest.mockReturnValue({ data: {} }));
it("empty data assertion", () => {/* ... */});
});
});发布于 2020-04-12 00:39:15
我建议尝试将FulfillmentService.getFullfillmentServices抽象出来,要么将其移到props中,要么创建上下文。这样,您就可以轻松地模拟来自FulfillmentService.getFullfillmentServices的每个响应。
第二种选择是使用nock并拦截FulfillmentService.getFullfillmentServices的api调用。
https://stackoverflow.com/questions/61142252
复制相似问题