我有课:
export default class A {
data: string
constructor(data?: any) {
if (data !== undefined) {
this.data = data.stingValue
}
}
}
然后我有另一个在公共方法中使用A
构造函数的类:
export default class B {
public doSomething(data: any) {
const a = new A(data)
dependecy.doAnotherThing(a)
}
}
并测试:
it(('shoud doSomething') => {
const doAnotherThingStub = stub(B.prototype, 'doAnotherThing')
//this part does not work, just an example of what I would like to achieve
const doAnotherThingStub = stub(A.prototype, 'constructor').returns({dataReturendFromAConstructorStub: true})
// end of this part
const b = new B()
b.doSomething({})
expect(doAnotherThingStub.calledWith({dataReturendFromAConstructorStub: true})).to.be.true
})
而且我的目标是将A类构造函数存根。我为A类进行了单独的测试,并且我不想再次对其进行测试。我需要类似stub(A.prototype,'constructor')
的内容。我尝试使用proxyquire
和存根,但是我无法注入伪造的构造函数,或者正在调用真实的构造函数,或者我得到的是类似的东西:A_1.default is not a constructor
。以前,我有一些案例需要对直接在测试用例中调用的类进行存根或对类的方法进行存根,这很简单。但是我正在为这种情况而苦苦挣扎。
模拟A
的正确方法是什么?
这里是使用proxyquire
和sinon
的单元测试解决方案:
a.ts
:
export default class A {
private data!: string;
constructor(data?: any) {
if (data !== undefined) {
this.data = data.stingValue;
}
}
}
b.ts
:
import A from './a';
export default class B {
public doSomething(data: any) {
const a = new A(data);
}
}
b.test.ts
:
import sinon from 'sinon';
import proxyquire from 'proxyquire';
describe('60152281', () => {
it('should do something', () => {
const aStub = sinon.stub();
const B = proxyquire('./b', {
'./a': {
default: aStub,
},
}).default;
const b = new B();
b.doSomething({});
sinon.assert.calledWithExactly(aStub, {});
});
});
带有覆盖率报告的单元测试结果:
60152281
✓ should do something (1908ms)
1 passing (2s)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 66.67 | 0 | 50 | 66.67 |
a.ts | 33.33 | 0 | 0 | 33.33 | 4,5
b.ts | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------