// processData.js code (all in the same file)
export const getCurrentTotals = async () => {
// setup etc.
const data = await s3.getObject(params).promise();
return JSON.parse(data.Body.toString('utf-8'));
};
export const calculateTotalsAndRecents = async (input) => {
const currentTotals = await getCurrentTotals();
// do calculations etc
// processData.test.js
import * as processData from './processData.js';
// ...
describe('#calculateTotalsAndRecents', () => {
beforeEach(() => {
const mock = jest.spyOn(processData, 'getCurrentTotals');
mock.mockImplementationOnce(() => Promise.resolve({}));
});
it('calculates totals', async () => {
const r = await processData.calculateTotalsAndRecents({ year: 2019, ...});
这里的问题是,在getCurrentTotals
中对calculateTotalsAndRecents
的调用总是调用实际的函数。我已经尝试了一些可能的修复方法,例如
How can I mock an ES6 module import using Jest?
Jest mock async function from default import
尝试在导入后添加jest.mock('./processData.js')
,但模拟了文件中的所有功能。我只想为一个测试覆盖文件中的一个功能。
我是否必须使用__mocks__
模拟整个文件,或者有更简单的方法来做到这一点?
答案 0 :(得分:0)
解决方案:
// __mocks__/s3Access.js
export const getCurrentTotals = jest.fn().mockImplementation(() => Promise.resolve({}));
export const putObjectToS3 = jest.fn().mockImplementation(() => Promise.resolve(true));
jest.mock('./s3Access.js');
import { getCurrentTotals, putObjectToS3 } from './s3Access.js';
beforeEach(() => {
getCurrentTotals.mockImplementationOnce(() => Promise.resolve(totals));
});
afterEach(() => {
getCurrentTotals.mockRestore();
});