【问题标题】:Mocha: Can't stub function in file that was already required in another test fileMocha:无法在另一个测试文件中已经需要的文件中存根函数
【发布时间】:2021-06-22 19:54:40
【问题描述】:

我正在使用 Mocha 在 fileToTest.js 上运行测试套件,需要 greeting.js

// --fileToTest.js--

const { greeting } = require('./greeting');

module.exports = () => greeting();
// --greeting.js--

module.exports.greeting = () => 'hi!';

这个测试文件本身成功存根greeting

// --test2.js--
let parent;
const sinon = require('sinon');
const chai = require('chai');
const greeting = require('../../greeting.js');

const { expect } = chai;

describe('stubbed /hi', () => {
  before(async () => {
    sinon.stub(greeting, 'greeting').callsFake((req, res, next) => 'bye!');
    parent = require('../../parent.js');
  });

  after(async () => {
    greeting.greeting.restore();
  });
  it('should say bye', async function () {
    expect(parent()).to.be.equal('bye!');
  });
});

但是,如果我运行一个测试套件并且有另一个需要 fileToTest.js 的测试文件,例如下面的 test1.js,那么上面的第一个测试 (test2.js) 将不会存根问候。

// --test1.js--
const chai = require('chai');
const fileToTest = require('../../fileToTest.js');

const { expect } = chai;

describe('not stubbed /hi', () => {
  it('should say hi', () => {
    expect(fileToTest()).to.be.equal('hi!');
  });
});

似乎一旦test1.js 需要fileToTest,mocha 就不会在test2.js 的需要上重新加载fileToTest。所以fileToTest 卡在了旧的问候功能上。

在这种情况下存根函数的正确方法是什么?

Repo

【问题讨论】:

    标签: node.js unit-testing mocking mocha.js sinon


    【解决方案1】:

    answer 工作。我不得不删除缓存。

      before(async () => {
        delete require.cache[require.resolve('../../fileToTest.js')]; // <------
    
        sinon.stub(greeting, 'greeting').callsFake((req, res, next) => 'bye!');
        fileToTest = require('../../fileToTest.js');
      });
    

    【讨论】:

      猜你喜欢
      • 2013-03-06
      • 2012-08-28
      • 2013-06-02
      • 1970-01-01
      • 1970-01-01
      • 2021-05-09
      • 2013-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多