//MyConfig.ts
export default function getConfig(name: string): string {
// do some logic
return var;
}
//MyUtil.ts
import getConfig from './MyConfig';
export default class MyUtil {
public static isFoo(): boolean {
const config = getConfig();
return config == 'Foo';
}
}
//MyUtil.test.ts
import MyUtil from '../MyUtil';
import * as config from '../MyConfig';
const configMock = config.default as jest.Mock;
describe('tests', () => {
it('blah', async () => {
configMock.mockReturnValue('mock-config');
const foo = MyUtil.isFoo();
});
});
I tried to mock getConfg function from MyConfig.ts in MyUtil.test.ts. I am getting an error 'configMock.mockReturnValue is not a function'.
How do I mock the export default function?
CodePudding user response:
You can use the direct function and assign the value in the spec file. Like
configMock = () => return 'mockConfig';
you don't need to use mockReturnValue for that case. Thanks.
CodePudding user response:
You will need to call jest.mock('../MyConfig')
in your test code.
See the jest documentation: https://jestjs.io/docs/mock-functions#mocking-modules
//MyUtil.test.ts
import MyUtil from '../MyUtil';
import * as config from '../MyConfig';
jest.mock('../MyConfig')
describe('tests', () => {
it('blah', async () => {
config.default.mockReturnValue('mock-config');
const foo = MyUtil.isFoo();
});
});