问题
我正在尝试模拟模块的默认导出部分,如下所示:
// test.js
const testVariable = {
blabla: {
test: 'testContent'
}
};
export const anotherNotNeedToMockVariable = {};
export default testVariable;
我实际需要模拟的变量是test.
我试过的
这个实现给了我一个错误:Cannot spy the default property because it is not a function
// toTestModule.js
import test from './test'
export const toTestModuleFunc = async () => {
console.log('variable mocked', test.blabla.test);
return test.blabla.test;
};
import * as test from '../test'
import {toTestModuleFunc} from '../toTestModule'
describe('test', () => {
it('with jest.mock()', async () => {
const newValue = 'newValue';
jest.mock('../test', () => ({
blabla: {
test: newValue
}
}));
const value = await toTestModuleFunc();
// this fails
expect(value).toEqual(newValue);
});
it('with jest.spyOn()', async () => {
const newValue = 'newValue';
jest.spyOn(test, 'default', 'get').mockImplementation(() => {
return ({
blabla: {
test: newValue
}
});
});
const value = await toTestModuleFunc();
// this fails
expect(value).toEqual(newValue);
});
});
如果我将其更改jest.spyOn(test, 'default')为jest.spyOn(test, 'default', 'get')它会给我另一个错误:Property default does not have access type get
我尝试使用jest.mock()函数,但它不起作用,它永远不会返回模拟值。
我真的很感激任何帮助。