测试一个React函数组件,表单提交中的这个组件调用了我嘲笑的助手API函数。
下面的代码给了我警告:测试中对SomeComponent的更新未包含在act(...)中。并且不会更新组件的状态。
组件伪代码
import React, { memo } from "react"
import { apiFunc } from "./API";
function SomeComponent() {
onSubmit = async () => {
const response = await apiFunc();
// DO something with response
}
return (
<form onSubmit={onSubmit}>
<input type="text" />
</form>
)
}
export default memo(SomeComponent)
笑话API模拟“ API / __ mocks __ / API”
export const apiFunc = () => {
return Promise.resolve({ message: "Success" });
};
笑话
jest.mock("./API")
describe("<SomeComponent />", () => {
it("Submits form", () => {
const wrapper = mount(<Component />);
wrapper
.find(`input[aria-label="${TEXTS.EMAIL}"]`)
.simulate("change", { target: { value: "[email protected]" } });
wrapper.find("form").simulate("submit");
expect(wrapper.find("div.fp-success")).toHaveLength(1);
});
});
describe('Scoped / Nested block', () => {
beforeAll(() => {
global.fetch = jest.fn().mockImplementation(() => //your function );
});
afterAll(() => {
global.fetch.mockClear();
delete global.fetch;
});
//your it
}
解决方案是按以下方式包装提交内容并调用强制状态更新
此外,您还需要React-dom 16.9及更高版本才能使用异步行为。
jest.mock("./API")
describe("<SomeComponent />", async () => {
it("Submits form", () => {
const wrapper = mount(<Component />);
wrapper
.find(`input[aria-label="${TEXTS.EMAIL}"]`)
.simulate("change", { target: { value: "[email protected]" } });
await act(async () => {
wrapper.find("form").simulate("submit");
});
act(() => {
wrapper.update();
});
expect(wrapper.find("div.fp-success")).toHaveLength(1);
});
});
希望这有助于其他开发人员寻找解决方案