如何用Jest模拟父类方法并验证其调用情况?
Jest 测试继承类中 super 方法的调用与模拟
一、验证 super.getOptions(params) 是否被调用
要验证子类B中调用了父类A的getOptions方法,核心是mock父类原型上的该方法,再断言其调用情况:
- 用
jest.spyOn监听父类A原型的getOptions方法并初始化mock:
jest.spyOn(A.prototype, 'getOptions').mockReturnValue({});
- 创建B的实例并调用目标方法:
const instanceB = new B(); instanceB.getOptions({ foo: 'bar' });
- 断言父类方法被正确调用,可同时验证参数匹配:
expect(A.prototype.getOptions).toHaveBeenCalled(); expect(A.prototype.getOptions).toHaveBeenCalledWith({ foo: 'bar' });
二、模拟 super.getOptions 的行为并修改返回值
通过mock可以自定义父类方法的返回结果或行为,满足不同测试场景:
1. 自定义返回值
模拟父类方法返回固定对象,验证子类是否正确合并属性:
// 设定父类方法的返回值 jest.spyOn(A.prototype, 'getOptions').mockReturnValue({ originalProp: 'originalValue' }); const instanceB = new B(); const result = instanceB.getOptions({}); // 断言子类返回结果包含父类返回值和新增属性 expect(result).toEqual({ originalProp: 'originalValue', newProperty: 'newProperty' });
2. 模拟异常抛出
测试子类在父类方法抛出错误时的处理逻辑:
// 模拟父类方法抛出错误 jest.spyOn(A.prototype, 'getOptions').mockImplementation(() => { throw new Error('super method error'); }); const instanceB = new B(); // 断言调用时会抛出对应错误 expect(() => instanceB.getOptions({})).toThrow('super method error');
三、测试后清理mock
为避免mock影响其他测试用例,建议在每个测试结束后恢复原方法:
afterEach(() => { A.prototype.getOptions.mockRestore(); });
内容的提问来源于stack exchange,提问作者tipiwiny
相关产品推荐
相关产品推荐

