#1使用笑话
这就是我使用笑话嘲笑回调函数来测试click事件的方式
import React from 'react';import { shallow } from 'enzyme';import Button from './Button';describe('Test Button component', () => { it('Test click event', () => { const mockCallBack = jest.fn(); const button = shallow((<Button onClick={mockCallBack}>Ok!</Button>)); button.find('button').simulate('click'); expect(mockCallBack.mock.calls.length).toEqual(1); });});我还使用了一个称为酶的模块
酶是一种测试实用程序,可让您更轻松地断言和选择您的React组件
#2使用Sinon
另外,您可以使用另一个称为sinon的模块,该模块是Javascript的独立测试间谍,存根和模拟。这是什么样子
import React from 'react';import { shallow } from 'enzyme';import sinon from 'sinon';import Button from './Button';describe('Test Button component', () => { it('simulates click events', () => { const mockCallBack = sinon.spy(); const button = shallow((<Button onClick={mockCallBack}>Ok!</Button>)); button.find('button').simulate('click'); expect(mockCallBack).toHaveProperty('callCount', 1); });});#3使用自己的间谍
最后,您可以使自己的天真间谍(除非您有充分的理由,否则我不建议您使用这种方法。)
function MySpy() { this.calls = 0;}MySpy.prototype.fn = function () { return () => this.calls++;}it('Test Button component', () => { const mySpy = new MySpy(); const mockCallBack = mySpy.fn(); const button = shallow((<Button onClick={mockCallBack}>Ok!</Button>)); button.find('button').simulate('click'); expect(mySpy.calls).toEqual(1);});


