【发布时间】:2019-08-09 04:54:28
【问题描述】:
我正在尝试测试是否使用酶和玩笑来调用 React 组件方法。当<section> 元素变得没有焦点(模糊)时,应该调用该函数。该组件连接到 Redux 存储,但它也按名称导出,以将 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.
【问题讨论】:
标签: javascript reactjs redux jestjs enzyme