我想重用一个变量,它在文件的beginnin中定义(在我的例子中,它是一个测试文件)。 对于某些测试,我必须更改对象的值,但这些更改只应针对此特定测试进行。下一个测试应该再次使用原始对象。
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()
})
})
我现在正在做的是首先定义&#39;默认&#39;对象(props
)在我的测试文件的开头。
每个测试都使用此对象。但是一些测试需要为特定元素获得不同的值。
在这种情况下,我要设置新值,例如在第一个测试中,我将id
设置为undefined
。
但在第二次测试中,我想使用&#39;默认&#39;再次反对。
在我的代码中,第二个测试也使用了新的undefined
(id)值,但我需要使用带有M1234567890
(id)值的原始对象。
答案 0 :(得分:2)
最好的方法是在beforeEach块中创建变量,这样每次测试都有一个干净的实例。特别是因为你不应该在每个测试中重复使用相同的间谍,这很容易隐藏错误的行为。
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()
})
})
答案 1 :(得分:0)
您可以使用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 {...Object.assign({}, props, {id: undefined})} />)
// 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()
})
})
,这对您的情况特别有帮助。
public function roles()
{
return $this->belongsToMany(Role::class, 'user_roles');
}
如果您想要进行更改,您可以传递要更改的属性,并且对象的其余部分将保持不变。