shallow淺渲染、render深渲染、mount測試交互
<div className={style.buttonWrap}>
<Tooltip title={tipsText} placement="top" {...tipsSetting}>
<Button
disabled={disabled}
onClick={() => {
handleClick(id);
}}
id={id}
>
{icon}
{text}
</Button>
</Tooltip>
</div>
1.組件中有兩個子組件組成,首先設(shè)置兩個測試用例,一個測試按鈕提示是否存在,一個測試按鈕是否存在,淺渲染因不會渲染子組件,所以這兩個用例使用shallow即可
注意find的時候選擇器應(yīng)當(dāng)是大駝峰的組件名稱,而不是html標(biāo)簽名稱button
it('should has Tooltip', () => {
const { wrapper } = setup();
expect(wrapper.find('Tooltip').length).toBe(1);
});
it('should has Button', () => {
const { wrapper } = setup();
expect(wrapper.find('Button').length).toBe(1);
});
2.測試按鈕文字內(nèi)容是否正確
經(jīng)審查元素,發(fā)現(xiàn)文字在多個標(biāo)簽里面,且在大的Button組件內(nèi)部,所以需要使用深渲染render,且選擇器為標(biāo)簽選擇器,而不為組件名。
it('should render button', () => {
const { wrapper } = setupByRender();
expect(wrapper.find('button').text()).toBe(props.text);
});
it('should render button icon', () => {
const { wrapper } = setupByRender();
expect(wrapper.find('button i').hasClass(props.iconName)).toBe(true);
});
3.mount測試交互
對該按鈕的交互測試需要模擬點擊事件,使用simulate方法,點擊斷言某個方法是否被調(diào)用,注意:模擬點擊的是按鈕組件,不是標(biāo)簽。
it('click item to be done', () => {
const { wrapper } = setupByMount();
wrapper
.find('Button')
.at(0)
.simulate('click');
expect(props.handleClick).toBeCalled();
});
關(guān)于enzyme的API exists,需要在mount中使用,否則報錯其不是一個方法。