为什么我的模块没有出现在 require.cache 中?

Why is my module not appearing in require.cache?

OS: Windows 10
节点版本:0.10.36
摩卡全球版本:1.21.4

我正在尝试使用 mocha 对我的代码进行单元测试,但我正在尝试测试的代码中的局部变量在测试之间持续存在,导致出现问题。

当我查看 require.cache 内部时,在测试之间,我没有在其中看到我的模块。据我了解,如果我想在测试之间重置此模块,我应该清除缓存。

我做了一个小节点项目来演示这个问题:

package.js:

{
    "name": "cache-test",
    "version": "0.0.1",
    "dependencies": {
        "lodash": "4.5.0"
    },
    "devDependencies": {
        "chai": "1.9.2",
        "mocha": "1.21.4",
        "mockery": "1.4.0",
        "sinon": "1.10.3",
        "app-root-path":"*"
    }
}

module.js:

var foo = "default value";

exports.init = function(){
    foo = 'init';
}

exports.returnFoo = function(){
    return foo;
}

test/test-module.js

var chai = require("chai"),
    expect = chai.expect,
    mockery = require("mockery"),
    appRoot = require('app-root-path');


var module;

describe("module", function () {

    before(function () {
        mockery.enable({ useCleanCache: true });
    });

    beforeEach(function () {
        mockery.registerAllowable(appRoot + "/module", true);
        module = require(appRoot + "/module");
    });

    afterEach(function () {
        console.log('deleting', require.cache[require.resolve(appRoot + "/module")]);
        delete require.cache[require.resolve(appRoot + "/module")];
        module = null;
        mockery.deregisterAll();
    });

    after(function () {
        mockery.disable();
    });

    describe("test",function(){
        it("foo should be 'init' after running init()",function(){
            module.init();
            console.log('foo is ',module.returnFoo());
            expect(module.returnFoo()).to.equal('init');
        });

        it("foo should be 'default value' if init() is not run",function(){
            console.log('foo is ',module.returnFoo());
            expect(module.returnFoo()).to.equal("default value");
        });
    });
});

运行 mocha 打印

  module
    test
foo is  init
      √ foo should be 'init' after running init()
deleting undefined
foo is  init
  1 failing

哦,我需要添加

mockery.resetCache() 到我的 afterEach 函数。那解决了。

似乎 useCleanCache 选项和从 require.cache 中删除条目彼此不兼容,因为前者阻止它出现在后者中。

所以它是:

  • 不要使用 useCleanCache
  • 从 require.cache
  • 中删除 "manually"

  • 使用useCleanCache
  • 使用 resetCache()

但不要试图混搭。