Вот решение для модульного тестирования в node
тестовой среде. Вы должны заглушить метод confirm
в переменной global
.
file.js
:
function writeTOFile(server, pin) {
let dContinue = confirm("You are uploading a file . Do you want to continue?");
if (dContinue) {
console.log("do something");
} else {
console.log("do another thing");
}
}
module.exports = { writeTOFile };
file.test.js
:
const sinon = require("sinon");
const file = require("./file");
describe("59883330", () => {
afterEach(() => {
sinon.restore();
});
it("should do something", function() {
global.confirm = sinon.stub().returns(true);
sinon.stub(console, "log");
file.writeTOFile("fghsssbn", "5647");
sinon.assert.calledWithExactly(global.confirm, "You are uploading a file . Do you want to continue?");
sinon.assert.calledWithExactly(console.log, "do something");
});
it("should do another thing", () => {
global.confirm = sinon.stub().returns(false);
sinon.stub(console, "log");
file.writeTOFile("fghsssbn", "5647");
sinon.assert.calledWithExactly(global.confirm, "You are uploading a file . Do you want to continue?");
sinon.assert.calledWithExactly(console.log, "do another thing");
});
});
Результаты модульного теста со 100% покрытием:
59883330
✓ should do something
✓ should do another thing
2 passing (11ms)
--------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
--------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
file.js | 100 | 100 | 100 | 100 | |
file.test.js | 100 | 100 | 100 | 100 | |
--------------|----------|----------|----------|----------|-------------------|
Если ваша тестовая среда browser
, метод confirm
существует в переменной window
.
Исходный код: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/59883330