javascript - 测试每种方法:使用 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();
});
解决方案
我不建议进行浅层测试,但这里有一个例子:
...
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);
})
})
取自链接
推荐阅读
- javascript - 使用Javascript将变量作为sqlite列名插入?
- matlab - 如果 A 是 B 的向量子集,我如何在 MATLAB 中找到 B 中 A 的索引?
- java - Java RMI NotBoundException?
- java - Java - 当我运行我的公式计算器程序时,即使选择了另一个形状,它也会默认询问“圆的半径是多少”
- flask - 在 Eve check_auth 方法中访问 Flask 请求对象
- loops - 自动将递归转换为迭代
- c++ - basic_string 到 basic_string_view 隐式转换...呃,为什么?
- javascript - 将节点 api 部署到 heroku 时遇到问题
- java - 如何获取 GPS 时间或网络时间,location.getTime() 返回错误的设备日期和时间
- c# - 如何在 UWP/C# 中使用 svg 文件资源设置 AppBarButton 图标