BSl*_*ink 4 mocking typescript jestjs ts-jest
假设我有一个结构如下的类:
// Some class that calls super.get() and adds an additional param
export default class ClassB extends ClassA {
private foo: string;
constructor(params) {
super(params);
this.foo = 'bar';
}
public async get(params?: { [key: string]: any }): Promise<any> {
return super.get({
foo: this.foo,
...params,
});
}
}
Run Code Online (Sandbox Code Playgroud)
我想测试是否使用提供的参数以及附加的{ foo: 'bar' }调用 super.get() 。
import ClassA from '../../src/ClassA';
import ClassB from '../../src/ClassB';
jest.mock('../../src/ClassA');
jest.unmock('../../src/ClassB');
describe('ClassB', () => {
describe('get', () => {
beforeAll(() => {
// I've tried mock implementation on classA here but didn't have much luck
// due to the extending not working as expected
});
it('should get with ClassA', async () => {
const classB = new ClassB();
const response = await classB.get({
bam: 'boozled',
});
// Check if classA fetch mock called with params?
});
});
});
Run Code Online (Sandbox Code Playgroud)
如何检查 classA.fetch 是否确实使用我期望的参数调用?
我是否做了一些完全错误的事情?
谢谢你的帮助!
您可以通过监视prototype
扩展类来完成此操作,如下所示:
const classASpy = jest.spyOn(ClassA.prototype, 'get');
classB.get(param)
expect(classASpy).toHaveBeenCalledWith(param);
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你!