Ang*_*ant 4 javascript unit-testing node.js jestjs node-config
我有以下 default/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 || '',
isVisible: process.env.IS_VISIBLE
};
Run Code Online (Sandbox Code Playgroud)
在我的 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')
}
Run Code Online (Sandbox Code Playgroud)
在我的单元测试中,我想测试 的两种情况isVisible,同时保持其他配置值不变。
我试过
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();
})
})
Run Code Online (Sandbox Code Playgroud)
这对我不起作用,并且它不会覆盖isVisible.
我知道我也可以模拟config.get像 那样的函数config.get.mockReturnValue(false),但这会覆盖cronInterval和queueName
这是我最近解决类似需求的一种方法(有条件地需要原始模块功能)......
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);
})
};
});
Run Code Online (Sandbox Code Playgroud)
然后在你的测试中:
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);
})
};
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
167 次 |
| 最近记录: |