我想重用一个在文件开头定义的变量(在我的例子中它是一个测试文件)。 对于某些测试,我必须更改对象的值,但这些更改只应针对此特定测试进行。下一次测试应该再次使用原始对象。
const props = {
id: 'M1234567890',
update: jest.fn()
}
describe('example()', () => {
it('should not call update if id is missing', () => {
// SETUP
props.id = undefined
const component = shallow(<Component {...props} />)
// EXECUTE
component.instance().example()
// VERIFY
expect(props.update).not.toHaveBeenCalled()
})
it('should call update', async () => {
// SETUP
const component = shallow(<Component {...props} />)
// EXECUTE
await component.instance().example()
// VERIFY
expect(props.update).toHaveBeenCalled()
})
})
我现在正在做的是首先在我的测试文件的开头定义“默认”对象 (props
)。
每个测试都使用这个对象。但是有些测试需要为特定元素获取不同的值。
在这种情况下,我正在设置新值,例如在第一个测试中,我将 id
设置为 undefined
。
但在第二次测试中我想再次使用“默认”对象。
在我的代码中,第二个测试也使用了新的 undefined
(id) 值,但我需要使用具有 M1234567890
(id) 值的原始对象。
最佳答案
最好的方法是在 beforeEach block 中创建变量,这样您在每个测试中都有一个干净的实例。特别是因为您不应该在每个测试中重复使用相同的 spy ,因为这很容易隐藏错误的行为。
describe('example()', () => {
let props
beforeEach(()=>{
props = {
id: 'M1234567890',
update: jest.fn()
}
})
it('should not call update if id is missing', () => {
// SETUP
props.id = undefined
const component = shallow(<Component {...props} />)
// EXECUTE
component.instance().example()
// VERIFY
expect(props.update).not.toHaveBeenCalled()
})
it('should call update', async () => {
// SETUP
const component = shallow(<Component {...props} />)
// EXECUTE
await component.instance().example()
// VERIFY
expect(props.update).toHaveBeenCalled()
})
})
关于javascript - 重复使用具有可选更改的已定义变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49768799/