我有以下要在Jest中测试的打字稿类。
//MyClass.ts
import { foo } from './somewhere/FooFactory';
export class MyClass {
private _state : number;
constructor( arg : string ) {
this._state = foo( arg );
}
public getState() : string {
return this._state;
}
}
这是我的测试
//MyClass.spec.ts
import { MyClass } from './MyClass';
describe( 'test MyClass', () => {
test( 'construct' => {
const c = new MyClass( 'test' );
expect( c ).toBeDefined();
expect( c.getState() ).toEqual( 'TEST' );
} );
} );
如何模拟MyClass中使用的foo函数,以便此测试通过?
答案 0 :(得分:5)
有几种不同的处理方法。
您只能使用jest.spyOn
和类似mockImplementation
之类的东西来模拟foo
:
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
});
});
类似地,您可以将FooFactory
与jest.mock
自动模拟,然后为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
});
});
您还可以使用传递给jest.mock
的模块工厂来模拟FooFactory
:
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
});
});
最后,如果您打算在多个测试文件中使用相同的模拟,则可以mock the user module,方法是在./somewhere/__mocks__/FooFactory.ts
创建模拟:
export function foo(arg: string) {
return 'TEST';
}
...然后调用jest.mock('./somewhere/FooFactory');
在测试中使用模拟:
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
});
});