这是我班上的一个例子:
class MyClass {
constructor() {
this.myLib = new MyLib()
}
myMainMethod = param => {
this.myLib.firstMethod(arg => {
this.myLib.secondMethod(arg)
})
}
}
使用玩笑,我如何断言我将调用“ myMainMethod”来调用“ secondMethod”。MyLib是第三方库。
index.ts
:
import { MyLib } from './MyLib';
export class MyClass {
myLib;
constructor() {
this.myLib = new MyLib();
}
myMainMethod = (param) => {
this.myLib.firstMethod((arg) => {
this.myLib.secondMethod(arg);
});
};
}
index.test.ts
:
import { MyClass } from './'; import { MyLib } from './MyLib'; describe('60840838', () => { it('should pass', () => { const firstMethodSpy = jest.spyOn(MyLib.prototype, 'firstMethod').mockImplementationOnce((callback) => { callback('arg'); }); const secondMethodSpy = jest.spyOn(MyLib.prototype, 'secondMethod').mockReturnValueOnce('fake'); const instance = new MyClass(); instance.myMainMethod('param'); expect(firstMethodSpy).toBeCalledWith(expect.any(Function)); expect(secondMethodSpy).toBeCalledWith('arg'); }); });
带有覆盖率报告的单元测试结果:
PASS stackoverflow/60840838/index.test.ts 60840838 ✓ should pass (4ms) ----------|---------|----------|---------|---------|------------------- File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s ----------|---------|----------|---------|---------|------------------- All files | 87.5 | 100 | 71.43 | 85.71 | MyLib.ts | 71.43 | 100 | 33.33 | 66.67 | 3,6 index.ts | 100 | 100 | 100 | 100 | ----------|---------|----------|---------|---------|------------------- Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 4.54s, estimated 8s