如何在reactjs单元测试中断言正确的值?

时间:2017-08-27 09:19:38

标签: javascript reactjs unit-testing

我已经用onClick事件编写了一个reactjs组件。这将更改组件中的文本,这是组件:

import React, {Component} from 'react'

export default class SimpleComponent extends Component{

constructor(props){
        super(props);
        this.state ={tekst:'leeg'}
}

handleClick = () =>{
        console.log('handleclick!!!');
        this.setState({tekst:'hallo'});
}

render() {
        return (
         <div>
            {this.state.tekst}
             simple comp
            <button onClick={this.handleClick} />   

         </div>
        )
      }
}

我写了一个单元测试来测试onClick事件:

import React from 'react';
import TestUtils from 'react-dom/test-utils';
import SimpleComponent from './SimpleComponent'
import expect from 'expect'

var renderer = TestUtils.createRenderer();

renderer.render(<SimpleComponent />);

var subject = renderer.getRenderOutput();

console.log(subject);

describe('Simple component',() => {
    it('should ...', () => {
        let btn = subject.props.children[2];
        btn.props.onClick();
        console.log('btn',btn)
        //let t = subject.props.children[0]
        //console.log('t',t)
        let tekst = subject.props.children[0]; 
        //console.log('tekst',tekst);
        expect(tekst).toEqual('hello');  // => true
    })
})

测试点击了handleClick事件,但是tekst仍然是旧的,它应该是&#39; hallo&#39;。如何测试handleClick?

更改state.tekst的情况

1 个答案:

答案 0 :(得分:0)

帮自己一个忙,并使用enzyme进行单元测试。它让生活更轻松。然后你可以这样写:

describe('<Foo />', () => {
  it('changes state on btn click', () => {
    const wrapper = shallow(<Foo />);
    wrapper.find('button').simulate('click');
    expect(wrapper.state().tekst).toBe('hallo');
  });
});