Javascript ecmascript中的模拟静态方法
我有一个在另一个类中使用的静态类。要进行单元测试,我需要模拟该类,但如何模拟呢Javascript ecmascript中的模拟静态方法,javascript,unit-testing,mocking,static-methods,Javascript,Unit Testing,Mocking,Static Methods,我有一个在另一个类中使用的静态类。要进行单元测试,我需要模拟该类,但如何模拟呢 import {StaticClass} from ''; class UserClass { method() { StaticClass.staticMethod(); } } it('should call staticMethod', () => { new UserClass().method(); expect(StaticClass.staticMethod).toH
import {StaticClass} from '';
class UserClass {
method() {
StaticClass.staticMethod();
}
}
it('should call staticMethod', () => {
new UserClass().method();
expect(StaticClass.staticMethod).toHaveBeenCalled();
})
您应该使用存根/模拟库,例如 例如 user.js: 从“/static”导入{StaticClass}; 导出类用户类{ 方法{ StaticClass.staticMethod; } } static.js: 导出类StaticClass{ 静力法{ log'staticmethodimplementation'; } } user.test.js: 从“./user”导入{UserClass}; 从“sinon”进口sinon; 从“/static”导入{StaticClass}; 描述'64135983',=>{ 它“应该通过”,=>{ const staticMethodStub=sinon.stubStaticClass,“staticMethod”; 新的UserClass.method; sinon.assert.calledOnCeStaticMethodSub; staticMethodStub.restore; }; }; 单元测试结果:
64135983
✓ should pass
1 passing (10ms)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 80 | 100 | 50 | 80 |
static.ts | 50 | 100 | 0 | 50 | 3
user.ts | 100 | 100 | 100 | 100 |
-----------|---------|----------|---------|---------|-------------------
很容易,我可以使用spyOn方法来检查我的方法是否被调用
spyOn(StaticClass, 'staticMethod').and.returnValue('mock value');
我还需要使用expect来检查是否已调用它
expect(StaticClass.staticMethod).toHaveBeenCalled();