你可以用
jest.doMock()
在单个单元测试用例中使用jest存根类的所有方法。
例如。
index.ts
:
export class SomeClass {
find() {
console.log('find');
}
findById(id) {
console.log('findById');
}
}
的真正实现
.find()
和
.findById
我们叫
console.log
现在,我们使用
jest.doMock
把它们剪短。
index.spec.ts
:
describe('57649917', () => {
it('should mock all methods of SomeClass', () => {
jest.doMock('./');
const { SomeClass } = require('./');
const logSpy = jest.spyOn(console, 'log');
const mInstance = new SomeClass();
expect(jest.isMockFunction(mInstance.find)).toBeTruthy();
expect(jest.isMockFunction(mInstance.findById)).toBeTruthy();
mInstance.find();
mInstance.findById(1);
expect(mInstance.find).toBeCalledTimes(1);
expect(mInstance.findById).toBeCalledTimes(1);
expect(logSpy).not.toBeCalled();
});
it('should call the real methods of SomeClass', () => {
jest.unmock('./');
const logSpy = jest.spyOn(console, 'log');
const { SomeClass } = require('./');
const instance = new SomeClass();
instance.find();
instance.findById(1);
expect(logSpy.mock.calls[0]).toEqual(['find']);
expect(logSpy.mock.calls[1]).toEqual(['findById']);
});
});
单元测试结果:
PASS src/stackoverflow/57649917/index.spec.ts (8s)
57649917
â should mock all methods of SomeClass (9ms)
â should call the real methods of SomeClass (9ms)
console.log node_modules/jest-mock/build/index.js:860
find
console.log node_modules/jest-mock/build/index.js:860
findById
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 9.182s
源代码:
https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/57649917
对于
sinon.js
,我们可以使用
sinon.createStubInstance
使用类的所有存根方法创建存根实例。
索引
:
查找(){
console.log('find');
}
log('findById');
}
}
:
import { SomeClass } from './';
import sinon from 'sinon';
import { expect } from 'chai';
describe('57649917', () => {
it('should stub all methods of SomeClass', () => {
const stubInstance = sinon.createStubInstance(SomeClass);
stubInstance.find();
stubInstance.findById(1);
expect(stubInstance.find.calledOnce).to.be.true;
expect(stubInstance.findById.calledWith(1)).to.be.true;
});
});
57649917
â should stub all methods of SomeClass
1 passing (13ms)
https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/57649917