首页 > 解决方案 > 测试每种方法:使用 Jest / 酶 for REACT JS

问题描述

我怎样才能为这两种方法实现正确的单元测试。我试图运行一些东西,但我认为调用该方法的方式不正确

 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();
});

标签: javascriptreactjsunit-testing

解决方案


我不建议进行浅层测试,但这里有一个例子:

...
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); 
    })
}) 

取自链接


推荐阅读