我试图编写一些测试,但我还没有找到如何从react-semantic-ui的Popup中获取trigger-element。有谁知道吗?
这是Popup;我想测试Icon
<Popup trigger={<Icon name='plus' color='green' onClick={this.followItem.bind(this)} />}
content='Follow this item' />
目前的测试方法:
describe('Follow Icon', () => {
it('should create a userItem when the follow icon is clicked', (done) => {
const wrapper = mount(<MemoryRouter><ItemDetails match={{ params: { id: 1 } }} /></MemoryRouter>);
const instance = wrapper.find(ItemDetails).instance();
instance.getItem().then(() => {
wrapper.update();
}).then(() => {
expect(wrapper.find(Popup)).toHaveLength(1);
const follow = shallow(wrapper.find(Popup).prop('trigger')());
// wrapper.find(...).prop(...) is not a function
expect(follow.props().name).toBe('plus');
done();
});
});
});
答案 0 :(得分:1)
我找到了一个有效的解决方案,但我不知道这是否是最佳做法。
<Popup trigger={<Icon id='follow'/>
const follow = wrapper.find(Popup).find('#follow').first();
由于某种原因,它确实在'#follow'中找到了2个元素,因此.first()是必需的;
如果有人找到更好的解决方案,请不要犹豫告诉我。
答案 1 :(得分:0)
最简单的方法是调用函数并浅显示结果。假设你有浅层渲染弹出窗口,只需调用trigger
函数并将结果传递给shallow
:
const icon = shallow(popup.prop('trigger')())
答案 2 :(得分:0)
我遇到了类似的问题,我测试Popup组件(使用您的示例)的解决方案是:
<Popup
trigger={<Icon
name='plus'
color='green'
onClick={this.followItem.bind(this)} />}
content={<div className="content">Follow this item</div>}
/>
// after setting the wrapper
// to test the trigger property, as this is always rendered we just need to:
expect(wrapper.find(Icon).prop().name).toBe('plus');
// to test the component property, as this gets rendered in the document.body,
// there is no way to assert on it using just one mount
const popupContentWrapper = mount(wrapper.find(Popup).instance().props.content);
expect(popupContentWrapper.find('.content').hostNodes()).toBeDefined()
// not sure if you notice the use of hostNodes here, but that's because find is
// returning both React components instances and DOM nodes, that match your query selector. hostNodes() solves the issue, reference: https://github.com/airbnb/enzyme/issues/836#issuecomment-401260477