Использование sinon.js
в качестве библиотеки утверждений. Кроме того, вы можете прочитать этот выпуск . Вот решение для модульного тестирования:
index.js
:
function function1() {}
function function2(arg) {}
class SomeClass {
topFunction(foo, bar) {
if (foo === bar) {
exports.function1();
}
exports.function2(foo);
}
}
exports.function1 = function1;
exports.function2 = function2;
exports.SomeClass = SomeClass;
index.test.js
:
const sinon = require("sinon");
const mod = require("./");
describe("59877615", () => {
afterEach(() => {
sinon.restore();
});
it("should call function1 and function2", () => {
const funtion1Stub = sinon.stub(mod, "function1");
const funtion2Stub = sinon.stub(mod, "function2");
const instance = new mod.SomeClass();
instance.topFunction("a", "a");
sinon.assert.calledOnce(funtion1Stub);
sinon.assert.calledOnce(funtion2Stub);
});
it("should only call function2", () => {
const funtion2Stub = sinon.stub(mod, "function2");
const instance = new mod.SomeClass();
instance.topFunction("a", "b");
sinon.assert.calledOnce(funtion2Stub);
});
});
Результаты модульного теста с отчетом о покрытии:
59877615
✓ should call function1 and function2
✓ should only call function2
2 passing (10ms)
---------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 71.43 | 100 | |
index.js | 100 | 100 | 33.33 | 100 | |
index.test.js | 100 | 100 | 100 | 100 | |
---------------|----------|----------|----------|----------|-------------------|
Исходный код: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/59877615