There are several approaches to tackle this issue.
You have the option to only mock foo
using jest.spyOn
in combination with mockImplementation
:
import { MyClass } from './MyClass';
import * as FooFactory from './somewhere/FooFactory';
describe('test MyClass', () => {
test('construct', () => {
const mock = jest.spyOn(FooFactory, 'foo'); // spy on foo
mock.mockImplementation((arg: string) => 'TEST'); // replace implementation
const c = new MyClass('test');
expect(c).toBeDefined();
expect(c.getState()).toEqual('TEST'); // SUCCESS
mock.mockRestore(); // restore original implementation
});
});
Alternatively, you can automatically mock FooFactory
using jest.mock
, then set an implementation for foo
:
import { MyClass } from './MyClass';
import * as FooFactory from './somewhere/FooFactory';
jest.mock('./somewhere/FooFactory'); // auto-mock FooFactory
describe('test MyClass', () => {
test('construct', () => {
const mockFooFactory = FooFactory as jest.Mocked<typeof FooFactory>; // get correct type for mocked FooFactory
mockFooFactory.foo.mockImplementation(() => 'TEST'); // provide implementation for foo
const c = new MyClass('test');
expect(c).toBeDefined();
expect(c.getState()).toEqual('TEST'); // SUCCESS
});
});
You also have the option to mock FooFactory
by using a module factory passed to jest.mock
:
import { MyClass } from './MyClass';
jest.mock('./somewhere/FooFactory', () => ({
foo: () => 'TEST'
}));
describe('test MyClass', () => {
test('construct', () => {
const c = new MyClass('test');
expect(c).toBeDefined();
expect(c.getState()).toEqual('TEST'); // SUCCESS
});
});
Lastly, if you intend to utilize the same mock in multiple test files you can mock the user module by creating a mock at
./somewhere/__mocks__/FooFactory.ts
:
export function foo(arg: string) {
return 'TEST';
}
...then invoke
jest.mock('./somewhere/FooFactory');
to apply the mock in the test:
import { MyClass } from './MyClass';
jest.mock('./somewhere/FooFactory'); // use the mock
describe('test MyClass', () => {
test('construct', () => {
const c = new MyClass('test');
expect(c).toBeDefined();
expect(c.getState()).toEqual('TEST'); // SUCCESS
});
});