我有一个组件,它有一个 prop 调用传递一个值的 prop 函数。 如何使用 enzyme 编写测试?
<LabeledInput
name='zip'
onChange={this.props.onChange}
onBlur={() => this.props.onBlur('zip')}
/>
beforeEach(() => {
props = {
onChange: sinon.spy(),
onBlur: sinon.spy(),
};
wrapper = shallowWithIntl(<ContactCard {...props}/>);
});
it('should call onChange prop', () => {
const labeledInputs = wrapper.find(LabeledInput);
let zipInput = labeledInputs.filterWhere(input => input.props().name === 'zip');
expect(zipInput.props().onChange).to.equal(props.onChange);
});
it('should onBlur prop ', () => {
const labeledInputs = wrapper.find(LabeledInput);
let zipInput = labeledInputs.filterWhere(input => input.props().name === 'zip');
expect(zipInput.props().onBlur).to.equal(props.onBlur);
});
第一个(onChange 测试)有效。 第二个给出错误“AssertionError: expected [Function: onBlur] to equal [Function: proxy]”
最佳答案
您正在比较 2 个不同的函数引用并试图断言它们相等。
onBlur={() => this.props.onBlur('zip')}
创建一个新的函数引用,然后调用 this.props.onBlur('zip')
在您的断言中,您正在尝试匹配 () => this.props.onBlur('zip') === this.props.onBlur('zip')
这将始终为 false .
FWIW [Function: proxy]
用于 spy 功能。
可能的修复,可能会在 onBlur prop 上寻找 toHaveBeenCalled
并使用这种方式断言。
在 Sinon 世界中,似乎使用以下三种之一:
expect(props.onBlur.called).to.equal(true);
sinon.assert.called(props.onBlur);
assert(props.onBlur.called);
关于reactjs - 我将如何测试组件 Prop 是否等于另一个 Prop 功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56261074/