UT散记
jestjs.io
一 常用
describe('', ()=>{test('test', ()=>{
expect(2+2).toBe(4)
expect(2+2).not.toBe(5)
expect(1).toBeTruthy()
expect(0).toBeFalsy()
expect(4).toBeGreaterThan(3)
expect(4).toBeLessThan(5)
expect({name:'viking'}).toEqual({name: 'viking'})
})
test('should trigger the correct function callbacks', ()=>{
const handleModifyItem = jest.fn();
const wrapper = shallow(<PriceListhandleModifyItem={handleModifyItem}/>)
wrapper.find('.submit').simulate('click')
expect(handleModifyItem).toHaveBeenCalledWith(1)
expect(handelClick).toHaveBeenCalledWith(
expexct.objectContaining({
'action': 'click',
'error': false0 07
})
)
})
})
Enzyme
let wrapper;describe('', ()=>{
beforeEach(()=>{
wrapper = shallow(<TotalPrive {...props} />)
})
test('should render the compoent to match snapshot', ()=>{
expect(wrapper).toMatchSnapshot()
})
test('test', ()=>{
expect(wrapper.find('.income span').text()).toEqual('1000')
})
test('should render correct icon and price for each item', ()=>{
const iconList = wrapper.find('list-item').first().find(Icon)
expect(iconList.length).toEqual(3)
})
test('click the year item, should trigger the right status change', ()=>{
wrapper.find('submit').sumilate('click')
expect(wrapper.find('.years-range').first().hasClass('active')).toEqual(true)
expect(wrapper.state('selectedYear')).toEqual(2014)
})
})
二 常见测试场景
01 模拟actions promise
import {Create} from'../Create';const history = {push:()=>{}}
const actions = {
getEditData: jest.fn().mockReturnValue(Promise.resole({editItem: testItem}))
}
describe('', ()=>{
it('', ()=>{
const wrapper = mount(
<Createactions={actions}history={history}/>
)
expect(actions.getEditData).toHaveBeenCalledWith(testItem.id)
})
})
02 mock input file
test('upload image, should return corrently value', done => {const mockFile = new File(['foo'], 'foo.png', {
type: 'image/png'
})
const props = {
updatePicture: ({picture, isError})=>{
expect(isError).toEqueal(false);
expect(picture).toBeTruthy();
done();
}
}
const UploadComponent = mount(<Upload {...props});
UploadComponent.find('.upload__file').simulate('change',{
target: {},
detaTransfer: {
files: [mockFile]
}
})
})
03 容器组件 test, 确认传入了正确的数据即可,组件内部有自己的UT
beforeEach(()=>{wrapper = shallow(<TotalPrive {...props} />)
})
test('should render the default layout', ()=>{
expect(wrapper.find(PriceList).length).toEqual(1)
expect(wrapper.find(ViewTab).props().activeTab).toEqual(LIST_VIEW)
})
三 UT 工具函数
exportconst getInputValue = (selector, wrapper) =>(wrapper.find(selector).instance().value
)
exportconst setInputValue = (selector, newValue, wrapper) =>{
wrapper.find(selector).instance().value = newValue
}
四 UT插件
02 jsdom 模拟DOM
2 Enzyme 组件rendering
Shallow Rendering 浅render
Full Rendering 深render
Static Rendering 静态render
3 Nock 模拟HTTP
4 Sinon 函数跟踪
5 Istanbul
以上是 UT散记 的全部内容, 来源链接: utcz.com/a/25806.html