gpt4 book ai didi

javascript - 在 Node.js 中模拟嵌套模块?

转载 作者:数据小太阳 更新时间:2023-10-29 06:05:42 28 4
gpt4 key购买 nike

我有这些文件:

文件1.js

var mod1 = require('mod1');
mod1.someFunction()
...

文件2.js

var File1 = require('./File1');

现在在为 File2 编写单元测试时,是否可以模拟 mod1,这样我就不会调用 mod1.someFunction()

最佳答案

我通常使用 mockery 模块,如下所示:

lib/file1.js

var mod1 = require('./mod1');
mod1.someFunction();

lib/file2.js

var file1 = require('./file1');

lib/mod1.js

module.exports.someFunction = function() {
console.log('hello from mod1');
};

测试/file1.js

/* globals describe, before, beforeEach, after, afterEach, it */

'use strict';

//var chai = require('chai');
//var assert = chai.assert;
//var expect = chai.expect;
//var should = chai.should();

var mockery = require('mockery');

describe('config-dir-all', function () {

before('before', function () {
// Mocking the mod1 module
var mod1Mock = {
someFunction: function() {
console.log('hello from mocked function');
}
};

// replace the module with mock for any `require`
mockery.registerMock('mod1', mod1Mock);

// set additional parameters
mockery.enable({
useCleanCache: true,
//warnOnReplace: false,
warnOnUnregistered: false
});
});

beforeEach('before', function () {

});

afterEach('after', function () {

});

after('after', function () {
// Cleanup mockery
after(function() {
mockery.disable();
mockery.deregisterMock('mod1');
});
});

it('should throw if directory does not exists', function () {

// Now File2 will use mock object instead of real mod1 module
var file2 = require('../lib/file2');

});

});

如前所述,sinon 模块构建模拟非常方便。

关于javascript - 在 Node.js 中模拟嵌套模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35138886/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com