解决方案是将模拟函数直接传递给子组件并对其进行测试。任何涉及多个“子组件”的内容通常都不是真正的单元测试,因为您正在测试多个功能单元。
所以我会创建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)
})
})
现在您缺少的断言是传递到成员列表的删除处理程序正确地传递给成员组件。所以让我们添加另一个测试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 或其他方式引导您完成。