这是我在很多测试中都会做的事情。我发现最适合我的方法是手动调用子组件的onChange
处理程序,并根据您期望结果发生的行为做出断言。
因此,假设您有一个如下所示的 Parent 组件:
import React from 'react';
import Child from './child';
export default class extends React.Component {
render() {
return (
<div>
<Child onChange={this.foo} />
</div>
);
}
foo() {
console.log('bar');
}
}
传递给 child的onChange
prop 将在调用时记录字符串 'bar'。这是我们要测试的行为。为此,我们需要采取以下步骤:
使用您选择的模拟库存根console.log
(我将在此示例中使用 Sinon)
创建 Parent 组件的浅实例,并获取对其 Child 的引用。
手动调用 Child 的onChange
道具。
被调用一次的断言console.log
,并带有一个参数:'bar'
这是我的做法(使用 mocha 和 chai):
import Foo from './foo';
import React from 'react';
import {shallow} from 'enzyme';
import sinon from 'sinon';
import sinonChai from 'sinon-chai';
import chai, {expect} from 'chai';
describe('Foo', () => {
let renderedElement;
function renderComponent() {
const componentElement = React.createElement(Foo);
renderedElement = shallow(componentElement);
}
before(() => {
chai.use(sinonChai);
});
it('should log the string "bar" when the child component is changed', () => {
//step 1
sinon.stub(console, 'log');
//step 2
renderComponent();
const childComponent = renderedElement.props().children;
//step 3
childComponent.props.onChange();
//step 4
expect(console.log).to.have.callCount(1);
expect(console.log).to.be.calledWith('bar');
//clean up
console.log.restore();
});
});
我喜欢这种方法的原因是因为它正在测试组件的行为,而不是简单地测试它是作为一个恰好等于另一个函数的 prop 传递的函数。