这是我的TS课
function func3(): string {
return ' some string'
}
function func4(){
func3()
}
export class classA implements ImyInterface {
public func1(): void { func4() }
public func2(): void {}
}
现在,我想编写测试以调用func1然后模拟func3不能与存根一起使用。
sandbox.stub(myInstance,"test3").returns("data");
如果我将func3移至classA,则func4找不到此类
答案 0 :(得分:0)
这是单元测试解决方案:
index.ts
:
function func3(): string {
return 'some string';
}
function func4() {
const rval = exports.func3();
console.log(rval);
}
interface ImyInterface {}
class classA implements ImyInterface {
public func1(): void {
exports.func4();
}
public func2(): void {}
}
exports.func3 = func3;
exports.func4 = func4;
exports.classA = classA;
index.spec.ts
:
import { expect } from 'chai';
import sinon from 'sinon';
const mod = require('./');
describe('t', () => {
it('should call stubbed methods correctly', () => {
const func3Stub = sinon.stub(mod, 'func3').returns('data');
const func4Spy = sinon.spy(mod, 'func4');
const logSpy = sinon.spy(console, 'log');
const instance = new mod.classA();
instance.func1();
expect(func4Spy.calledOnce).to.be.true;
expect(func3Stub.calledOnce).to.be.true;
expect(logSpy.calledWith('data')).to.be.true;
});
});
带有覆盖率报告的单元测试结果:
t
data
✓ should call stubbed methods correctly
1 passing (16ms)
---------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files | 95.83 | 100 | 71.43 | 95.83 | |
index.spec.ts | 100 | 100 | 100 | 100 | |
index.ts | 90.91 | 100 | 60 | 90.91 | 2 |
---------------|----------|----------|----------|----------|-------------------|
源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/57589200