我正在使用 Jest + 测试库/React 编写功能测试。经过几天的绞尽脑汁,我发现当你使用.mockResolvedValue(...)
or .mockResolvedValueOnce(...)
嘲笑的范围不仅限于该测试......
import React from "react";
import { render, waitForElement } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import myApi from '../myApi';
jest.mock('../myApi'); // this will load __mocks__/myApi.js (see below)
import { wait } from '@testing-library/dom';
import App from "../components/App";
afterEach(() => {
jest.clearAllMocks();
});
describe("App", () => {
test("first test", async () => {
myApi.get.mockResolvedValueOnce('FOO');
// App will call myApi.get() once
const { container, getByText } = render(<App />);
await waitForElement(
() => getByText('FOO')
);
expect(myApi.get).toHaveBeenCalledTimes(1);
// This is going to "leak" into the next test
myApi.get.mockResolvedValueOnce('BAR');
});
test("second test", async () => {
// This is a decoy! The 'BAR' response in the previous test will be returned
myApi.get.mockResolvedValueOnce('FOO');
// App will call myApi.get() once (again)
const { container, getByText } = render(<App />);
// THIS WILL FAIL!
await waitForElement(
() => getByText('FOO')
);
expect(myApi.get).toHaveBeenCalledTimes(1);
});
});
这是什么__mocks__/myApi.js
好像:
export default {
get: jest.fn(() => Promise.resolve({ data: {} }))
};
我明白发生了什么:myApi
被导入到两个测试的共享范围中。这就是为什么.mockResolvedValue*
适用于“跨”测试。
防止这种情况的正确方法是什么?测试应该是原子的,并且不能相互耦合。如果我触发另一个get
请求在first test
它不应该被打破second test
。太臭了!但什么是正确的模式呢?我正在考虑克隆不同的“副本”myApi
进入本地测试范围......但我担心这会变得奇怪并导致降低我的测试的信心。
I found 这个问题 https://stackoverflow.com/questions/46855281/scoping-in-jest-when-mocking-functions它讨论了相同的主题,但仅解释了为什么会发生这种情况,而不是讨论避免这种情况的正确模式。
包.json
"dependencies": {
"axios": "^0.18.1",
"moment": "^2.24.0",
"react": "^16.11.0",
"react-dom": "^16.11.0",
"react-redux": "^7.1.3",
"react-router-dom": "^5.1.2",
"react-scripts": "2.1.5",
"redux": "^4.0.4",
"redux-thunk": "^2.3.0"
},
"devDependencies": {
"@testing-library/jest-dom": "^4.2.3",
"@testing-library/react": "^9.3.2",
"redux-mock-store": "^1.5.3",
"typescript": "^3.7.2"
}