Функция замены заглушки Sinon не работает

Я изолировал проблему, с которой столкнулся в своих узлах здесь. Заглушка Sinon для зависимой функции не работает должным образом. Я не понял, чего мне здесь не хватает. Цените помощь. Вот пример кода.

sinontest.js

"use strict";
function getSecretNumber () {
  return 44;
}
function getTheSecret () {
  return `The secret was: ${getSecretNumber()}`;
}

module.exports = {
  getSecretNumber,
  getTheSecret,
};

sinonTest_spec.ts

"use strict";
const sinon = require("sinon");
const sinonMediator = require("./sinonTest");
const assert = require("assert");

describe("moduleUnderTest", function () {
  describe("when the secret is 3", function () {
    beforeEach(function () {
      sinon.stub(sinonMediator, "getSecretNumber").returns(3);
    });
    afterEach(function (done) {
      sinon.restore();
      done();
    });
    it("should be returned with a string prefix", function () {
      const result = sinonMediator.getTheSecret();
      const stubValue = sinonMediator.getSecretNumber();    
      assert.equal(stubValue, 3);                         //this assertion passed
      assert.equal(result, "The secret was: 3");          //but this assertion failed.
    });
  });
});

Вот ошибка утверждения, которую я получаю, когда выполняю тестовый пример.

AssertionError [ERR_ASSERTION]: 'The secret was: 44' == 'The secret was: 3'

Спасибо.


person NKS    schedule 02.04.2020    source источник


Ответы (1)


Это обычное поведение, когда вы require используете модуль. Дополнительные сведения: https://nodejs.org/docs/latest/api/modules.html#modules_exports_shortcut

function require(/* ... */) {
  const module = { exports: {} };

  ((module, exports) => {
    function getSecretNumber() {
      return 44;
    }
    function getTheSecret() {
      return `The secret was: ${getSecretNumber()}`;
    }
    module.exports = {
      getTheSecret,
      getSecretNumber,
    };
  })(module, module.exports);

  return module.exports;
}

Вы можете заглушить метод module.exports.getSecretNumber, но функция getSecretNumber, вызываемая внутри getTheSecret, по-прежнему является исходной функцией, а не заглушкой. Вот почему твоя заглушка не работает.

index.js:

'use strict';
function getSecretNumber() {
  return 44;
}
function getTheSecret() {
  return `The secret was: ${exports.getSecretNumber()}`;
}

exports.getSecretNumber = getSecretNumber;
exports.getTheSecret = getTheSecret;

index.test.js:

'use strict';
const sinon = require('sinon');
const sinonMediator = require('./');
const assert = require('assert');

describe('moduleUnderTest', function() {
  describe('when the secret is 3', function() {
    beforeEach(function() {
      sinon.stub(sinonMediator, 'getSecretNumber').returns(3);
    });
    afterEach(function(done) {
      sinon.restore();
      done();
    });
    it('should be returned with a string prefix', function() {
      const result = sinonMediator.getTheSecret();
      const stubValue = sinonMediator.getSecretNumber();
      assert.equal(stubValue, 3); 
      assert.equal(result, 'The secret was: 3');
    });
  });
});

результаты модульного теста с отчетом о покрытии:

  moduleUnderTest
    when the secret is 3
      ✓ should be returned with a string prefix


  1 passing (25ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |      75 |      100 |      50 |      75 |                   
 index.js |      75 |      100 |      50 |      75 | 3                 
----------|---------|----------|---------|---------|-------------------
person slideshowp2    schedule 02.04.2020
comment
Понятно!! и спасибо @slideshowp2 за такое хорошее объяснение. - person NKS; 02.04.2020