React Enzyme Props 未设置在 Mount 上
React Enzyme Props Not Set on Mount
我正在为呈现图表并对其执行一些操作的 HOC 编写单元测试。该图表是使用从数据库获取并存储在 redux-store 中的数据生成的。出于测试目的,我创建了一个假数据存储,但是图表的加载数据发生在 componentDidMount 并通过检查道具的值来执行。所以我的代码如下:
...
ComponentDidMount()
{
console.log(this.props.getData);
if (this.props.getData === "YES")
this.props.loadData();
}
...
而我单元测试中的代码如下:
...
const mockStore = configureStore([thunk]);
let fakeStore = mockStore({...});
it("loads data"), function() {
let store = fakeStore;
const options = {
context: {store},
childContextTypes: {store: PropTypes.object.isRequired},
};
const mounted = mount(<Component getData="YES"/>, options);
console.log(mounted.props());
mounted.instance().componentDidMount();
}
...
问题是使用 console.log 我可以看到当组件第一次挂载时没有设置 props 和 componentDidMount 运行s 自动,尽管我指定了一些值,但 props 紧随其后,并且当我尝试调用该函数时,它没有 运行,但没有显示任何消息来解释为什么它没有。
有人可以指点一下吗?
您可以使用 sinon library 模拟外部交互。然后检查组件渲染时是否调用了模拟交互。您正在编写的是单元测试而不是端到端测试。所以应该是这样的。
import React from 'react'
import YourComponent from 'components/YourComponent'
import { shallow } from 'enzyme'
describe('(Component) YourComponent', () => {
let _props, _spies, _wrapper
beforeEach(() => {
_spies = {}
_props = {
prop1: 'value1',
prop2: 'value2',
...
getData : (_spies.getData = sinon.spy()),
}
_wrapper = shallow(<YourComponent {..._props} />)
})
it('Should trigger the `getData` callback when mounted', () => {
_spies.getData.should.have.been.called
})
})
希望这对您有所帮助。编码愉快!
我正在为呈现图表并对其执行一些操作的 HOC 编写单元测试。该图表是使用从数据库获取并存储在 redux-store 中的数据生成的。出于测试目的,我创建了一个假数据存储,但是图表的加载数据发生在 componentDidMount 并通过检查道具的值来执行。所以我的代码如下:
...
ComponentDidMount()
{
console.log(this.props.getData);
if (this.props.getData === "YES")
this.props.loadData();
}
...
而我单元测试中的代码如下:
...
const mockStore = configureStore([thunk]);
let fakeStore = mockStore({...});
it("loads data"), function() {
let store = fakeStore;
const options = {
context: {store},
childContextTypes: {store: PropTypes.object.isRequired},
};
const mounted = mount(<Component getData="YES"/>, options);
console.log(mounted.props());
mounted.instance().componentDidMount();
}
...
问题是使用 console.log 我可以看到当组件第一次挂载时没有设置 props 和 componentDidMount 运行s 自动,尽管我指定了一些值,但 props 紧随其后,并且当我尝试调用该函数时,它没有 运行,但没有显示任何消息来解释为什么它没有。
有人可以指点一下吗?
您可以使用 sinon library 模拟外部交互。然后检查组件渲染时是否调用了模拟交互。您正在编写的是单元测试而不是端到端测试。所以应该是这样的。
import React from 'react'
import YourComponent from 'components/YourComponent'
import { shallow } from 'enzyme'
describe('(Component) YourComponent', () => {
let _props, _spies, _wrapper
beforeEach(() => {
_spies = {}
_props = {
prop1: 'value1',
prop2: 'value2',
...
getData : (_spies.getData = sinon.spy()),
}
_wrapper = shallow(<YourComponent {..._props} />)
})
it('Should trigger the `getData` callback when mounted', () => {
_spies.getData.should.have.been.called
})
})
希望这对您有所帮助。编码愉快!