测试每种方法:使用Jest /酶进行REACT JS

时间:2019-01-29 14:10:23

标签: javascript reactjs unit-testing

如何为这两种方法实施正确的单元测试。我尝试运行一些操作,但是我认为调用方法不是正确的方法

 componentDidMount () {
this.setState({
  defaultData: this.props.defaultData
})
}

 componentWillReceiveProps(nextProps){
this.setState({
  defaultData: nextProps.defaultData
})

}

例如,我可以沿这些方式实现某些方法来调用方法吗?测试目前通过了,但我不认为正在检查方法

 it (' ComponentWillReceiveProps : should return correct', () => {
  const wrapper = shallow(<Component {...baseProps } />);  
  wrapper.setState({test: 'test'});
  expect(wrapper.instance().componentWillReceiveProps('test')).toEqual();
});

1 个答案:

答案 0 :(得分:0)

我不建议进行浅层测试,但这是一个示例:

...
componentWillMount() {
    this.logUserId(this.props.userId);
}
componentWillReceiveProps(nextProps) {
    if (this.props.userId !== nextProps.userId) {
        this.logUserId(nextProps.userId);
    }
}
logUserId(userId) {
    console.log(userId);
}
...

import SomeComponent from ‘./SomeComponent’;
import { shallow } from ‘enzyme’;
describe('componentWillReceiveProps()', () => {
    it('call logUserId once', () => {
        const logUserId =
           sinon.stub(SomeComponent.prototype, ‘logUserId’);
        let userId = '123';
        const component = shallow(<SomeComponent userId={userId}/>;
// resetting call count from componentWillMount()
        logUserId.reset();
userId = '456';
        // triggers componentWillReceiveProps
        component.setProps({ userId });
// PASS!
        expect(logUserId).to.be.calledOnce.and.calledWith(userId); 
    })
}) 

取自link