[英]unit testing the output of a form in React.js, Jest, Enzyme
我正在 React 中构建一个简单的 todo 应用程序,我也在使用酶进行测试。 我刚刚将 reder 列表提取到了它自己的反应组件中,它工作正常。 我正在尝试对此组件的输出进行模拟测试,但我正在努力。
我运行测试时的当前结果是
Expected: "New Note"
Received: <p><button onClick={[Function onClick]}>X</button></p>
测试目前看起来像这样......
describe('ListItems', () => {
let wrapper;
beforeEach(() => {
const items = ['New Note', 'efefre', 'efqeecec'];
wrapper = shallow(<ListItems list={[items]} />);
});
it('renders title of application', () => {
expect(wrapper.find("h1").text()).toContain("This is the list")
});
it('renders the new note on the page', () => {
const items = ['New Note']
const wrapper = shallow(<ListItems list={items} />)
const textOutput = wrapper.find("#text-output")
expect(textOutput.props().children).toEqual("New Note")
})
});
正如你所看到的,我试图用“新注释”模拟一个新数组,在我的测试中传递了一个对象,但不是实际的消息。 我哪里错了?
以防万一它有帮助这是我要测试的文件..
import React from 'react';
function ListItems(props) {
const list = props.list
const displayItems = list.map((item, index) =>
{
return <div id='text-output' key={index}>
<p>
{item.body}
<button
onClick={ () => props.deleteItem(item.id)}>
X
</button>
</p>
</div>
})
return(
<div>
<h1>This is the list</h1>
{displayItems}
</div>
)
}
如果有人可以提供帮助,那就太好了。
您正在传递一个带有字符串["New note"]
的数组,但您的代码实际上需要一个带有主体和 ID 的对象数组。 然后尝试(但失败)呈现"New note".body
,因为该属性不存在。 这就是您看到此输出的原因:
<p><button onClick={[Function onClick]}>X</button></p>
如果您将["New note"]
替换为[{body: "New note", id: "some-id"}]
,您的输出将看起来更像这样,我相信这就是您所期望的:
<p>New note<button onClick={[Function onClick]}>X</button></p>
当然,当您在包装器上找到 div ID 时,您将获得 p 和 button 元素。 如果您需要在作为 items 数组传入时断言 p 元素具有文本“新注释”。 你应该用这个
...
const textEl = wrapper.find("#text-output p"); // returns p element
expect(textEl.text()).toBe("New note");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.