<section>元素失焦(on blur)时,该函数应该被调用。该组件连接到Redux store,但也按名称导出,以将Redux从方程式中剔除。以下是组件的简化版本:
export class Section extends React.Component {
constructor(props) {
super(props)
this.formRef = React.createRef();
this.submitForm = this.submitForm.bind(this);
this.state = {
formSubmitted: false
}
}
submitForm() {
console.log("form submitted");
this.setState({ formSubmitted: true })
if (this.formRef && this.formRef.current) {
this.formRef.current.submit();
}
}
render() {
return (
<section onBlur={this.submitForm}>
<form ref={this.formRef} action={url} method='post'>
<input type="text" name="something" />
</form>
</section>
);
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(Section);
我尝试了各种spyOn的组合,因为它似乎是问题的根源。但所有的尝试都失败了。
import React from 'react';
import { shallow } from 'enzyme';
import { Section } from './Section';
describe('Section', () => {
it('should submit form on blur', () => {
const wrapper = shallow(<Section content={{ body: [] }} />);
const spy = spyOn(wrapper.instance(), 'submitForm');
const spy2 = spyOn(Section.prototype, 'submitForm');
const spy3 = jest.spyOn(wrapper.instance(), 'submitForm');
const spy4 = jest.spyOn(Section.prototype, 'submitForm');
wrapper.find('section').simulate('blur');
expect(wrapper.state().formSubmitted).toEqual(true);
expect(spy).toHaveBeenCalled();
expect(spy2).toHaveBeenCalled();
expect(spy3).toHaveBeenCalled();
expect(spy4).toHaveBeenCalled();
})
})
我给这个组件添加了一个状态并进行了测试,除了测试 expect(...).toHaveBeenCalled 以验证函数是否被实际调用,看起来是这样的。
在控制台中出现了 console.log('form submitted')。
测试 expect(wrapper.state().formSubmitted).toEqual(true); 通过,这表明正确的函数被调用了。然而,我不希望为了测试而有一个不必要的状态。状态只是为了断言 "submitForm" 方法是否被调用而添加的。
所有的断言 expect(...).toHaveBeenCalled() 都失败,并显示错误信息 Expected spy to have been called, but it was not called 或 Expected mock function to have been called, but it was not called.
React文档,@AndreiDotsenko 问:在渲染方法中使用箭头函数是否可以? "一般来说,是可以的"。如果您遇到性能问题,那么请移除箭头函数,但通常性能成本非常小。 - Brian Adams