[英]How do I test super calls when using Typescript with Jest?
Say I have a class that's structured like this:假设我有一个结构如下的类:
// 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,
});
}
}
I would like to test that super.get() was called with the provided parameters as well as the additional { foo: 'bar' } .我想测试使用提供的参数以及附加的{ 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?
});
});
});
How do I check that classA.fetch was actually called with the params I'm expecting?我如何检查 classA.fetch 实际上是用我期望的参数调用的?
Am I doing anything that's just completely wrong?我在做任何完全错误的事情吗?
Thanks for any help!谢谢你的帮助!
You can accomplish this by spying on the prototype
of the extended class, something like this:您可以通过监视扩展类的
prototype
来完成此操作,如下所示:
const classASpy = jest.spyOn(ClassA.prototype, 'get');
classB.get(param)
expect(classASpy).toHaveBeenCalledWith(param);
Hope it helps!希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.