[英]Test function with Jest in React Js
I'm new to React and testing in general so forgive the naivety of the question. 我是React和测试的新手,所以请原谅这个问题的天真。 I have a React form component which
onChance
on the inputs runs a function handleChange
. 我有一个阵营形式部件
onChance
输入端上的运行的函数handleChange
。 Tried to test it with Jest but can't make it work. 试图用Jest测试它,但无法使其正常工作。
Here's the Login component: 这是登录组件:
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;
Here's my test: 这是我的测试:
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();
})
The snapshot test passes fine, but in this last attempt my function test fails with: 快照测试通过正常,但是在这最后一次尝试中,我的功能测试失败并显示以下信息:
TypeError: Cannot read property 'target' of undefined
Guess I need to pass something to the function? 猜猜我需要向函数传递一些东西吗? Bit confused!
有点困惑!
Thanks in advance for your help. 在此先感谢您的帮助。
UPDATE: 更新:
changed the test as follows but test fails with: expect(jest.fn()).toBeCalled() Expected mock function to have been called.
改变了如下测试,但测试失败:
expect(jest.fn()).toBeCalled() Expected mock function to have been called.
test updated: 测试已更新:
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();
})
Yes, you'll need to pass an event object to you simulate
function. 是的,您需要将事件对象传递给您的
simulate
功能。
const event = {target: {name: "special", value: "party"}};
element.simulate('change', event);
EDIT: Oh, and you'll also need to do something like: 编辑:哦,您还需要执行以下操作:
jest.spyOn(login.instance(), 'handleChange')
but that's unrelated to your error 但这与您的错误无关
handleChange
isn't currently being mocked. 目前尚未嘲笑
handleChange
。 A couple of approaches: 几种方法:
Pass change event handler as prop to
Login
component.将更改事件处理程序作为prop传递给
Login
组件。
<div className="input-group">
<input
onChange={this.props.handleChange}
value={this.state.username}
className="form-control login__input username"
type="text"
placeholder="user name"
name={'username'}
autoFocus
/>
</div>
login.spec.js login.spec.js
...
const handleChange = jest.fn();
const login = mount(<Login handleChange={handleChange}/>);
...
Replace handleChange with the mock function.
用模拟功能替换handleChange。
...
const handleChange = jest.fn();
const login = mount(<Login />);
login['handleChange'] = handleChange // replace instance
...
expect(handleChange).toBeCalled();
Use jest
spyOn
to create a mock function that wraps the original function.使用jest
spyOn
创建一个包装原始函数的模拟函数。
...
const handleChange = jest.spyOn(object, 'handleChange') // will call the original method
expect(handleChange).toBeCalled();
Replace
handleChange
on the Login component with a mock function.用模拟函数替换Login组件上的
handleChange
。 ... const handleChange = jest.spyOn(object, 'handleChange').mock // will call the original method expect(handleChange).toBeCalled();... const handleChange = jest.spyOn(object,'handleChange')。mock //将调用原始方法Expect(handleChange).toBeCalled();
Found the solution in here: Enzyme simulate an onChange event 在这里找到解决方案: 酶模拟onChange事件
test('Input should call handleChange on change event', () => {
const event = {target: {name: 'username', value: 'usertest'}};
const login = mount(<Login />);
const handleChange = jest.spyOn(login.instance(), 'handleChange');
login.update(); // <--- Needs this to force re-render
const userInput = login.find('.username');
userInput.simulate('change', event);
expect(handleChange).toBeCalled();
})
It needed this login.update();
它需要这个
login.update();
in order to work! 为了工作!
Thank everyone for your help! 感谢大家的帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.