我的考试对象是loader.ts
:
import * as dotenv from 'dotenv';
export class SimpleLoader {
public load() {
dotenv.config(); // I want to spy on this call
}
}
因此,使用Sinon.JS(与Mocha&Chai一起),我在loader.spec.ts
中进行了以下操作:
import * as dotenv from 'dotenv';
import * as sinon from 'sinon';
describe('SimpleLoader', function() {
// First spy on, then require SimpleLoader
beforeEach(function() {
this.dotenvSpy = sinon.spy(dotenv, 'config');
this.SimpleLoader = require('./loader').SimpleLoader;
});
it('loads correctly using default options', function() {
const loader = new this.SimpleLoader();
loader.load(); // the call that should call the spy!
console.log(this.dotenvSpy.getCalls()); // NOT WORKING - no calls, empty array []
});
afterEach(function() {
this.dotenvSpy.restore();
});
});
问题在于,永远不会调用存根。
答案 0 :(得分:0)
这是一个可行的示例,只需将import * as dotenv from 'dotenv'
更改为import dotenv from 'dotenv'
:
loader.ts
:
import dotenv from 'dotenv';
export class SimpleLoader {
public load() {
dotenv.config();
}
}
loader.spec.ts
:
import dotenv from 'dotenv';
import sinon from 'sinon';
import { expect } from 'chai';
describe('SimpleLoader', function() {
beforeEach(function() {
this.dotenvSpy = sinon.spy(dotenv, 'config');
this.SimpleLoader = require('./loader').SimpleLoader;
});
it('loads correctly using default options', function() {
const loader = new this.SimpleLoader();
loader.load();
expect(this.dotenvSpy.calledOnce).to.be.true;
});
afterEach(function() {
this.dotenvSpy.restore();
});
});
覆盖率100%的单元测试结果:
SimpleLoader
✓ loads correctly using default options
1 passing (152ms)
----------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
loader.spec.ts | 100 | 100 | 100 | 100 | |
loader.ts | 100 | 100 | 100 | 100 | |
----------------|----------|----------|----------|----------|-------------------|
源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/56427984