我对 React 和一般测试都很陌生,所以请原谅这个问题的天真。我有一个 React 表单组件,其输入上的 onChance
运行一个函数 handleChange
。尝试用 Jest 测试它,但无法使其工作。
这是登录组件:
class Login extends React.Component {
constructor() {
super();
this.state = {username: '', password: ''}
this.disableSubmit = this.disableSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.setState({
[e.target.name]: e.target.value
});
}
render() {
return(
<div className="login">
<form>
<h3 className="login__title">LOGIN</h3>
<div className="input-group">
<input onChange={this.handleChange} value={this.state.username} className="form-control login__input username" type="text" placeholder="user name" name={'username'} autoFocus/>
</div>
<div className="input-group">
<input onChange={this.handleChange} value={this.state.password} className="form-control login__input password" type="password" placeholder="password" name={'password'}/>
</div>
<div>
<button className="btn btn-primary btn-block login__button" type="submit">Login</button>
</div>
</form>
</div>
)
}
}
export default Login;
这是我的测试:
import React from 'react'
import { shallow, mount } from 'enzyme'
import { shallowToJson } from 'enzyme-to-json'
import {Login} from '../../../src/base/components/index'
describe('Given the Login component is rendered', () => {
describe('Snapshots', () => {
let component
beforeEach(() => {
component = shallow(<Login />)
})
it('should be as expected', () => {
expect(shallowToJson(component)).toMatchSnapshot()
})
})
})
test('Submitting the form should call handleSubmit', () => {
const startState = {username: ''};
const handleChange = jest.fn();
const login = mount(<Login />);
const userInput = login.find('.username');
userInput.simulate('change');
expect(handleChange).toBeCalled();
})
快照测试顺利通过,但在最后一次尝试中,我的功能测试失败了:
TypeError: Cannot read property 'target' of undefined
我想我需要向函数传递一些东西?有点困惑!
预先感谢您的帮助。
更新:
按如下方式更改测试,但测试失败:expect(jest.fn()).toBeCalled() 预期已调用模拟函数。
测试更新:
test('Input should call handleChange on change event', () => {
const login = mount(<Login />);
const handleChange = jest.spyOn(login.instance(), 'handleChange');
const userInput = login.find('.username');
const event = {target: {name: "username", value: "usertest"}};
userInput.simulate('change', event);
expect(handleChange).toBeCalled();
})
最佳答案
是的,您需要将事件对象传递给您的模拟
函数。
const event = {target: {name: "special", value: "party"}};
element.simulate('change', event);
编辑:哦,您还需要执行以下操作:
jest.spyOn(login.instance(), 'handleChange')
但这与您的错误无关
关于javascript - 在 React Js 中使用 Jest 测试函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46243243/