使用jest和酶的反应组分方法的测试用例

时间:2018-04-03 11:57:37

标签: javascript reactjs unit-testing enzyme jest

我是单元测试的新手。我有一个反应组件

export default class Login extends Component{
  constructor(){
    super()
    this.state={
      email: '',
      password:'',
      validFields: false
    }
    
    this.handleChangeInput = this.handleChangeInput.bind(this);
  }
  
  handleChangeInput(e){
    const name = e.target.name;
    const value = e.target.value;
    this.setState({[name]: value});
    if (this.state.email.length>0 &&         this.state.password.length>0 ) {
      this.setState({validFields: true});
    } else {
      this.setState({validFields: false});
    }
  }
  
  render() {
    return (
      <div>
        <form onSubmit={this.handleLoginSubmit}>
          <div className="input">
            <input id="email" type="text" name ="email" placeholder="Email" value={this.state.email} onChange={this.handleChangeInput}/>
          </div>
          <div className="input">
            <input id="password" type="password" name="password" placeholder="Password" value={this.state.password} onChange={this.handleChangeInput}/>
          </div>
          <input id="submitButton" type="submit" value ="LOG IN" disabled={!this.state.validFields}/>
        </form>
      </div>
    )
  }
}

现在我想测试函数handleChangeInput(e)。任何人都可以帮助模拟该功能的测试用例吗?我正在使用开玩笑和酶。

1 个答案:

答案 0 :(得分:0)

首先,你的方法进行2次setState调用,这是次优的。

要在开玩笑测试用例中测试它,您可以遵循此指南(阅读jest doc以了解如何编写更好的测试https://facebook.github.io/jest/docs/en/tutorial-react.html):

describe('<Login>', () => {

    describe('handleChangeInput', () => {

        const component = new Login()

        beforeEach(() => {
            component.setState = jest.fn()
        })

        test('calls setState validFields false when no email/password', () => {
            const state = { state : { email: '', password: ''} }
            const args = { target : { name: 'name', value: 'value' } }
            component.handleChangeInput.call(state, args)
            expect(component.setState.mock.calls.length).toBe(2)
            expect(component.setState.mock.calls[1][0]).toEqual({validFields:false})
        })

        test('calls setState validFields true when email/password are ok', () => {
            const state = { state : { email: 'email', password: 'password' } }
            const args = { target : { name: 'name', value: 'value' } }
            component.handleChangeInput.call(state, args)
            expect(component.setState.mock.calls.length).toBe(2)
            expect(component.setState.mock.calls[1][0]).toEqual({validFields:true})
        })
})

(代码未经测试)