好的,我已经根据与 OP 的讨论更新了我的答案。被测组件有一个 redux 提供者和连接的组件作为子组件,因此我们选择使用酶浅 API。
关于跟踪和测试,addEventListener
您可以使用该sinon
库创建一个间谍,它暂时“替换” window.addEventListener
. 这使您可以访问调用计数以及调用它的参数。
使用酶和摩卡咖啡,我创建了以下测试,这些测试对我来说是通过的。前两个测试涵盖了上述所有案例,为了更好地衡量,我添加了另一个关于如何测试someFunction
.
import React from 'react';
import { expect } from 'chai';
import sinon from 'sinon';
import { shallow } from 'enzyme';
// Under test.
import SampleComponent from './SampleComponent';
describe('SampleComponent', () => {
let addEventListenerSpy;
beforeEach(() => {
// This replaces the window.addEventListener with our spy.
addEventListenerSpy = sinon.spy(window, 'addEventListener');
});
afterEach(() => {
// Restore the original function.
window.addEventListener.restore();
});
// This asserts your No 1.
it(`should set the property`, () => {
const wrapper = shallow(<SampleComponent />);
wrapper.instance().componentDidMount(); // call it manually
expect(wrapper.instance().property).equal('property');
});
// This asserts your No 2 and No 3. We know that by having
// passed the someFunction as an argument to the event listener
// we can trust that it is called. There is no need for us
// to test the addEventListener API itself.
it(`should add a "scroll" event listener`, () => {
const wrapper = shallow(<SampleComponent />);
wrapper.instance().componentDidMount(); // call it manually
expect(addEventListenerSpy.callCount).equal(1);
expect(addEventListenerSpy.args[0][0]).equal('scroll');
expect(addEventListenerSpy.args[0][1]).equal(wrapper.instance().someFunction);
expect(addEventListenerSpy.args[0][2]).true;
});
it(`should return the expected output for the someFunction`, () => {
const wrapper = mount(<SampleComponent />);
expect(wrapper.instance().someFunction()).equal('hello');
});
});
值得注意的是,我在节点上运行测试,但我的配置中有一个jsdom
设置mocha
,这可能是负责创建window.addEventListener
在我的测试环境中使用的候选。您是通过浏览器还是节点运行测试?如果节点你可能需要做一些类似于我的事情。