componentDidMount
调用调用api的商店fetchVersionsRequest
功能fetchVersionsRequest
使用Promise all
在承诺解决后由商店更新@observer
将再次调用组件呈现,因为all
已更新请检查评论
@inject('versionStore') @observer
export default class extends Component {
componentDidMount() {
const { fetch } = this.props.versionStore;
fetch(); // Will call api.fetchVersionsRequest
}
render() {
// all is an array updated after call api.fetchVersionsRequest resolved
const { all } = this.props.versionStore;
// ...
return {all.map(it => <p>{it.name}</p>)}
}
}
如何测试组件是否正确呈现?
我想使用Snapshot功能,给出api返回的列表,组件应该是快照
我的测试主页组件
it('renders versions', function() {
const versions = [
{ id: 1, name: 'version1' },
{ id: 2, name: 'version2' },
];
api.fetchVersionsRequest = jest.fn(() => {
return Promise.resolve(versions);
});
const wrapper = shallow(<Home {...this.minProps} />);
expect(toJson(wrapper)).toMatchSnapshot(); // PROBLEM Snapshot does not contain any p element
}
答案 0 :(得分:2)
向您展示如何在开玩笑中使用承诺。你必须从测试中返回承诺,让jest知道它必须等待它。
it('renders versions', function() {
const versions = [
{ id: 1, name: 'version1' },
{ id: 2, name: 'version2' },
];
const p = Promise.resolve(versions);
api.fetchVersionsRequest = jest.fn(() => {
return p
});
const wrapper = shallow(<Home {...this.minProps} />);
return p.then(()=>{
expect(toJson(wrapper)).toMatchSnapshot();
})
}
或
it('renders versions', async function() {
const versions = [
{ id: 1, name: 'version1' },
{ id: 2, name: 'version2' },
];
const p = Promise.resolve(versions);
api.fetchVersionsRequest = jest.fn(() => {
return p
});
const wrapper = shallow(<Home {...this.minProps} />);
a
expect(toJson(wrapper)).toMatchSnapshot();
}
文档中解释了here
答案 1 :(得分:0)
而不是使用jest.fn来模拟来自API的数据。您可以使用 wrapper.setProps 直接设置道具来测试您的组件:
const wrapper = shallow(<Home {...this.minProps} />);
wrapper.setProps({
versionStore: {
all: versions
}
});
expect(toJson(wrapper)).toMatchSnapshot();