Javascript jest中的模拟特定配置值
我有以下默认的/config.js文件Javascript jest中的模拟特定配置值,javascript,node.js,unit-testing,jestjs,node-config,Javascript,Node.js,Unit Testing,Jestjs,Node Config,我有以下默认的/config.js文件 /* eslint-disable @typescript-eslint/no-var-requires */ require('dotenv').config({ path: require('find-config')('.env'), }); module.exports = { cronInterval: process.env.CRON_INTERVAL, queueName: process.env.QUEUE_NAME || '
/* eslint-disable @typescript-eslint/no-var-requires */
require('dotenv').config({
path: require('find-config')('.env'),
});
module.exports = {
cronInterval: process.env.CRON_INTERVAL,
queueName: process.env.QUEUE_NAME || '',
isVisible: process.env.IS_VISIBLE
};
在我的index.ts中,我有
import config from 'config';
import * as cron from 'node-cron';
const isVisible = config.get<boolean>('isVisible');
const queueName = config.get<string>('queueName');
const cronInterval = config.get<string>('cronInterval');
function startProcess(queueName) {
cron.schedule(cronInterval, () => {});
}
// process starts here
if (isVisible) {
startProcess(queueName);
} else {
logger.info('Wont start')
}
这对我不起作用,并且它不会覆盖isVisible
的值
我知道我也可以模拟
config.get
函数,比如config.get.mockReturnValue(false)
,但这将覆盖cronInterval
和queueName
的值。我最近解决了一个类似的需求(有条件地需要原始模块功能)
然后在你的测试中:
it('isVisible=true',()=>{
isVisible=true;
//这里测试逻辑
});
它('isVisible=false',()=>{
isVisible=false;
//这里测试逻辑
});
config.get()方法来自哪里?你是如何在你的index.ts
文件中导入config
模块的?@slideshowp2这是配置包@angulardubutant,请将const
更改为let
forisVisible
并导入该文件并尝试更改其值。你知道你的代码有一个输入错误,对吗?“isVibible:false”谢谢,但出于某种原因,只有第一次测试运行。我不知道这是否与require('./../src/index')有关代码>?但是文件中的代码在两个测试中只调用一次..模拟只知道你给它的路径。。。所以require('./../src/index')
不同于require('config')
。另外,一般来说,模拟函数比导出对象/数组更容易。我最终做的事情有点不同,但我接受了你的答案,因为它解决了最初的问题。谢谢
describe.only('isVisible', () => {
beforeEach(() => {
jest.mock('./../config/default.js', () => ({
isVisible: false
}));
})
it('should not run anything if not visible', () => {
require('./../src/index');
const scheduleSpy = jest.spyOn(cron, 'schedule');
expect(scheduleSpy).not.toHaveBeenCalled();
})
})
let isVisible = false;
jest.mock('config', () => {
// Require the original module!
const originalConfig = jest.requireActual('config');
return {
__esModule: true, // for esModules
get: jest.fn((key: string) => {
// override result conditionally on input arguments
if (key === 'isVisible') return isVisible;
// otherwise return using original behavior
return originalModule.get(key);
})
};
});