test('test equal', ()=> {
expect(2+2).toBe(4)
})
test('test not equal', ()=> {
expect(2+2).not.toBe(5)
})
test('test to be true or false', ()=> {
expect(1).toBeTruthy()
expect(0).toBeFalsy()
})
test('test number', ()=>{
expect(4).toBeGreaterThan(3)
expect(4).toBeLessThan(5)
})
text('test object', ()=>{
expect({name:'viking'}).toBe({name:'viking'})
expect({name:'viking', age:30}).toEqual({name:'viking', age:30})
} )
Enzyme
Shallow Rendering - 不会渲染子组件
DOM Rendering - 渲染子组件
import {configure} from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
configure({adapter: new Adapter()})
UT用例分析
- 传入特定数组 是否渲染对应程度的条目
- 每个条目是否渲染特定组件和内容
- 点击按钮是否触发特定回调
测试回调函数
it('should trigger the correct function callbacks', ()=>{
const firstItem = wrapper.find('.list-item').first()
firstItem.find('a').first().simulate('click')
expect(props.onModifyItem).toHaveBeenCalledWith(1)
})
DOM环境
handleClick = (evnet) => {
if(this.node.contains(event.target)){
return;
}
this.setState({
isOpen: false
})
}
it('after the dropdown is shown, click the document should close', ()=>{
let eventMap = {}
document.addEventListener = jest.fn((event, cb)=>{
eventMap[evnet] = cb
})
const wrapper = mount(<com {...props} />)
eventMap.click(){
target: ReactDOM.findDOMNode(wrapper.instance())
}
expect(wrapper.state('isOpen')).toEqual(true)
eventMap.click(){
target: document,
}
expect(wrapper.state('isOpen')).toEqual(false)
})
容器组件