Helpers.spec.js文件
describe('Helpers', () => {
beforeAll(() => {
jest.clearAllMocks();
jest.mock('./operations', () => ({
Operators: jest.fn()
}));
});
afterEach(() => {
jest.clearAllMocks();
});
const mockData = [ { id: 1 }, { id: 2 }, { id: 3 } ];
it('Should return a id 1', async () => {
Operations.getData = jest.fn().mockResolvedValue(mockData);
const response = await Helpers.execute();
expect(response.id).toBe(1);
});
it('Should return a id 1 with true flag', async () => {
Operations.getData = jest.fn().mockResolvedValue(mockData);
Operations.track = jest.fn().mockResolvedValue({});
const response = await Helpers.execute(true);
expect(response.id).toBe(1);
});
});
Helpers.js
import { getData, track } from `./operations`;
export class Helpers {
static async execute(request) {
if(request)
track();
const data = getData();
return data.shift();
}
}
Operation.js
async function getData() {
// Operation to return the data
}
async function track() {
// Operation to track the data
}
这里第二个测试用例失败了,因为它返回了id 2。由于某种原因,当第二个测试用例正在运行时,mockData
数组由于第一个测试用例而被移动了一次。
1条答案
按热度按时间34gzjxbg1#
1.您应该使用
const data = await getData()
,因为getData
函数是async
。1.您应该为每个测试用例创建
mockData
,以便在一个测试用例中对它进行变异(data.shift()
)不会影响其他测试用例。1.将
jest.mock()
放入测试文件的模块范围。helpers.js
:operations.js
:helpers.test.js
:试验结果: