我是React和測試的新手,因此原諒了這個問題的天真性。我有一個React表單組件,其輸入上的onChance
運行功能handleChange
。試圖用Jest來測試它,但不能使它工作。React Js中的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
猜猜我需要傳遞一些東西給函數?有點困惑!
在此先感謝您的幫助。
UPDATE:
改變了如下測試,但測試失敗:expect(jest.fn()).toBeCalled() Expected mock function to have been called.
測試更新:
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();
})
'handleChange'目前沒有被模擬。 –