我使用Jest来测试我的React组件。但是,我不知道(或者没有看到任何东西)如何测试将方法传递给子组件的组件(作为prop)。例如,我有:Form
,MemberList
,Member
,FormButton
。代码中与此类似的东西:
形式:
<MemberList members={this.state.members} remove={this.remove} add={this.add} />
<FormButton data={this.state.members} />
会员:
<span onClick={this.add}> <!-- add button --> </span>
{this.props.members.map(function(member, index) {
<Member key={index} data={member} remove={this.props.remove} />
})}
成员:
// some input like name and so, and a remove itself button.
FormButton:
var submit = function() {
this.setState({ loading: true });
// xhr
}
<button type="button" onClick={submit} disabled={this.state.loading}>Submit</button>
我是否以正确的心态思考?要补充一点,那里有实际的例子吗?
*我在尝试React和Jest之前从未测试过。
答案 0 :(得分:5)
解决方案是将模拟函数直接传递给子组件并测试它们。涉及多个&#34;子组件&#34;通常不是真正的单元测试,因为您正在测试多个功能单元。
所以我会创建MemberList-test.js
:
describe('MemberList', function () {
it('calls the add handler when add is clicked', function () {
var Component = TestUtils.renderIntoDocument(
<MemberList add={ jest.genMockFn() } />
);
const btn = TestUtils.findRenderedDOMComponentWithTag(Component, 'span')
TestUtils.Simulate.change(btn);
expect(Component.add.mock.calls.length).toBe(1)
})
})
然后,您应该创建Member-test.js
,而不是尝试直接在同一测试中测试您的成员组件:
describe('Member', function () {
it('calls the add handler when add is clicked', function () {
var Component = TestUtils.renderIntoDocument(
<Member remove={ jest.genMockFn() } />
);
const btn = TestUtils.findRenderedDOMComponentWithTag(Component,
'HOWEVER YOU FIND YOUR REMOVE BUTTON')
TestUtils.Simulate.change(btn);
expect(Component.remove.mock.calls.length).toBe(1)
})
})
现在你缺少的断言是传递给成员列表的remove处理程序正确地传递给Member组件。因此,让我们为MemberList-test.js
it('passes correct information to the children', function () {
var MemberMock = require('../Member')
var removeFn = jest.genMockFn();
var testMember = {WHATEVER YOUR MEMBER OBJECT LOOKS LIKE}
var Component = TestUtils.renderIntoDocument(
<MemberList members={ [testMember] }
remove={ removeFn } />
);
// We expect the member component to be instantiated 1 time and
// passed the remove function we defined
// as well as a key and the data
expect(MemberMock.mock.calls).toEqual([[{key: 0, data: testMember,
remove: removeFn}]])
})
然后,您只需使用表单组件执行相同的模式。模拟成员列表和按钮并单独测试它们,看到正确的处理程序和数据传递下来。
希望这是有道理的,如果不仅仅是回复,也许我可以通过Skype或其他方式引导您完成。