我目前第一次用jest和nodejs介绍自己。我面临的问题是,我必须模拟nodejs配置中的两个不同值。
jest.mock('config')
mockConfigTtl = require('config').get.mockReturnValue(100);
mockConfigScheduling = require('config').get.mockReturnValue('* * * * *');
问题是第二个mockReturnValue覆盖了第一个。有没有可能把展台模型彼此分开?
也许有这样的东西:
jest.mock('config')
mockConfigTtl = require('config').get('firstKey').mockReturnValue(100);
mockConfigScheduling = require('config').get('secondKey').mockReturnValue('* * * * *');
由于您希望确保您的实现能够使用所有可能的配置,我认为最好在不同的描述块中设置多个测试场景,并且在每个测试场景中使用mockReturnValue
并执行您的实现。
示例:
const config = require('config');
jest.mock('config')
describe('my implementation', () => {
describe('with firstKey 100', () => {
let result
beforeAll(() => {
config.get.mockReturnValue(100)
result = myImplementation()
})
it('should result in ...', () => {
// your assertion here
})
})
describe('with firstKey different than 100', () => {
let result
beforeAll(() => {
config.get.mockReturnValue(1000)
result = myImplementation()
})
it('should result in ...', () => {
// your assertion here
})
})
})
或者,如果你想测试更多的配置,你可以使用describe.each
const config = require('config');
jest.mock('config')
describe('my implementation', () => {
describe.each([
100,
200,
300
])('with firstKey: %d', (firstKey) => {
let result
beforeAll(() => {
config.get.mockReturnValue(firstKey)
result = myImplementation()
})
it('should match the snapshot', () => {
expect(result).toMatchSnapshot()
})
})
})
它将生成一个快照,其中包含您实现的结果,如果它更改了测试,则除非快照更新,否则测试将失败
您还可以使用config.get.mockImplementation(()=>'dummyData')
传递数据进行测试。
如果在某些情况下你需要原始数据,你可以在测试中使用这个片段:
config.get.mockImplementation((key) => {
const originalModule = jest.requireActual('config')
return originalModule.get(key)
})