Mocha:无法在另一个测试文件中已经需要的文件中存根函数 [英] Mocha: Can't stub function in file that was already required in another test file
问题描述
我正在使用 Mocha 在 fileToTest.js
上运行测试套件,需要 greeting.js
I'm using Mocha to run a test suite on fileToTest.js
with requires greeting.js
// --fileToTest.js--
const { greeting } = require('./greeting');
module.exports = () => greeting();
// --greeting.js--
module.exports.greeting = () => 'hi!';
就其本身而言,这个测试文件成功地存根了greeting
.
By itself, this test file successfully stubs 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
) 不会存根问候.
However if I run a test suite and have another test file that requires fileToTest.js
, like test1.js
below, the first test above (test2.js
) won't stub greeting.
// --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
卡住了旧的问候功能.
It seems once test1.js
requires fileToTest
, mocha doesn't reload the fileToTest
on the test2.js
's require. So fileToTest
is stuck with the old greeting function.
在这种情况下存根函数的正确方法是什么?
Whats the proper way to stub a function in this situation?
推荐答案
这个 answer 有效.我不得不删除缓存.
This answer worked. I had to delete the cache.
before(async () => {
delete require.cache[require.resolve('../../fileToTest.js')]; // <------
sinon.stub(greeting, 'greeting').callsFake((req, res, next) => 'bye!');
fileToTest = require('../../fileToTest.js');
});
这篇关于Mocha:无法在另一个测试文件中已经需要的文件中存根函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!