ReferenceError: подтверждение не определено - PullRequest
0 голосов
/ 23 января 2020

Я запускаю модульный тест для функции, используя mocha. Я вижу эту ошибку ReferenceError: подтверждение не определено . Как решить эту проблему?

файл. js

function writeTOFile(server, pin) {
  let dContinue = confirm("You are uploading a file . Do you want to continue?");
  if(dContinue) {
   //do something
  } else {
   ....
  }        
}

** test.spe c. js

let file = require("file.js");
const expect = require('chai').expect;

it('test something',function (){
file.writeTOFile("fghsssbn", "5647");
expect(somevalue).to.be(something);
})

Когда я запускаю тест мокко. js, я вижу выше, как пройти через эту ошибку.

1 Ответ

1 голос
/ 26 января 2020

Вот решение для модульного тестирования в 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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...