正如其他人所展示的那样,将传递给/的回调块包装起来process.nextTick
或setImmediate
在try
/ 中catch
起作用,但这是冗长且分散注意力的。
一个清洁的方法是使用简单的线齐平的Promiseawait new Promise(setImmediate);
内部async
测试回调。这是一个使用它来让 HTTP 请求useEffect
(对于componentDidMount
)解析并在运行断言之前触发重新渲染的工作示例:
组件 ( LatestGist.js
):
import axios from "axios";
import React, {useState, useEffect} from "react";
export default () => {
const [gists, setGists] = useState([]);
const getGists = async () => {
const res = await axios.get("https://api.github.com/gists");
setGists(res.data);
};
useEffect(() => {
getGists();
}, []);
return (
<>
{gists.length
? <div data-test="test-latest-gist">
the latest gist was made on {gists[0].created_at}
by {gists[0].owner.login}
</div>
: <div>loading...</div>}
</>
);
};
测试 ( LatestGist.test.js
):
import React from "react";
import {act} from "react-dom/test-utils";
import Enzyme, {mount} from "enzyme";
import Adapter from "enzyme-adapter-react-16";
Enzyme.configure({adapter: new Adapter()});
import mockAxios from "axios";
import LatestGist from "../src/components/LatestGist";
jest.mock("axios");
describe("LatestGist", () => {
beforeEach(() => jest.resetAllMocks());
it("should load the latest gist", async () => {
mockAxios.get.mockImplementationOnce(() =>
Promise.resolve({
data: [
{
owner: {login: "test name"},
created_at: "some date"
}
],
status: 200
})
);
const wrapper = mount(<LatestGist />);
let gist = wrapper
.find('[data-test="test-latest-gist"]')
.hostNodes()
;
expect(gist.exists()).toBe(false);
await act(() => new Promise(setImmediate));
wrapper.update();
expect(mockAxios.get).toHaveBeenCalledTimes(1);
gist = wrapper
.find('[data-test="test-latest-gist"]')
.hostNodes()
;
expect(gist.exists()).toBe(true);
expect(gist.text()).toContain("test name");
expect(gist.text()).toContain("some date");
});
});
使用类似的行强制失败的断言expect(gist.text()).toContain("foobar");
不会导致套件崩溃:
● LatestGist › should load the latest gist
expect(string).toContain(value)
Expected string:
"the latest gist was made on some date by test name"
To contain value:
"foobar"
at Object.it (src/LatestGist.test.js:30:25)
这是我的依赖项:
{
"dependencies": {
"axios": "^0.18.0",
"react": "^16.8.6",
"react-dom": "^16.8.6"
},
"devDependencies": {
"enzyme": "3.9.0",
"enzyme-adapter-react-16": "1.12.1",
"jest": "24.7.1",
"jest-environment-jsdom": "24.7.1"
}
}