Javascript 单元测试React.js、Jest、Enzyme中表单的输出
我正在react中构建一个简单的todo应用程序,我也在使用酶进行测试。我刚刚将reder列表提取到它自己的react组件中,该组件工作良好。我试图模拟测试这个组件的输出,但我很挣扎 运行测试时的当前结果是Javascript 单元测试React.js、Jest、Enzyme中表单的输出,javascript,reactjs,unit-testing,jestjs,enzyme,Javascript,Reactjs,Unit Testing,Jestjs,Enzyme,我正在react中构建一个简单的todo应用程序,我也在使用酶进行测试。我刚刚将reder列表提取到它自己的react组件中,该组件工作良好。我试图模拟测试这个组件的输出,但我很挣扎 运行测试时的当前结果是 Expected: "New Note" Received: <p><button onClick={[Function onClick]}>X</button></p> 应为“新注释” 收到:X 测试当前看起来像这样
Expected: "New Note"
Received: <p><button onClick={[Function onClick]}>X</button></p>
应为“新注释”
收到:X
测试当前看起来像这样
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")
})
});
description('ListItems',()=>{
让包装纸;
在每个之前(()=>{
常量项=['newnote','efefefre','efqeecec'];
包装器=浅();
});
它('呈现应用程序的标题',()=>{
expect(wrapper.find(“h1”).text()).toContain(“这是列表”)
});
它('在页面上呈现新注释',()=>{
常量项=['新注释']
常量包装器=浅()
const textOutput=wrapper.find(“文本输出”)
expect(textOutput.props().children).toEqual(“新注释”)
})
});
正如您所看到的,我试图用一个“newnote”来模拟一个新数组,在我的测试中传递了一个对象,但不是实际的消息。我哪里做错了
以防万一,这是我要测试的文件
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>
)
}
从“React”导入React;
功能列表项(道具){
const list=props.list
const displayItems=list.map((项目,索引)=>
{
返回
{item.body}
props.deleteItem(item.id)}>
X
})
返回(
这是名单
{displayItems}
)
}
如果有人能帮上忙,那就太好了。您正在传递一个带有字符串的数组
[“New note”]
,但您的代码实际上需要一个带有主体和id的对象数组。然后它尝试(但失败)呈现“New note”。主体
,因为该属性不存在。这就是您看到此输出的原因:
<p><button onClick={[Function onClick]}>X</button></p>
您正在传递一个字符串为
[“New note”]
的数组,但您的代码实际上需要一个带有主体和id的对象数组。然后,它尝试(但失败)呈现“New note”.body
,因为该属性不存在。这就是您看到此输出的原因:
<p><button onClick={[Function onClick]}>X</button></p>
当然,当您在包装器上找到div ID时,您将获得p和button元素。如果需要断言p元素,则在作为items数组传入时,该元素具有文本“newnote”。你应该用这个
。。。
const textEl=wrapper.find(“#文本输出p”)//返回p元素
expect(textEl.text()).toBe(“新注释”);
当然,当您在包装器上找到div ID时,您将获得p和button元素。如果需要断言p元素,则在作为items数组传入时,该元素具有文本“newnote”。你应该用这个
。。。
const textEl=wrapper.find(“#文本输出p”)//返回p元素
expect(textEl.text()).toBe(“新注释”);