【问题标题】:unit testing the output of a form in React.js, Jest, Enzyme在 React.js、Jest、Enzyme 中对表单的输出进行单元测试
【发布时间】:2020-09-14 16:12:19
【问题描述】:

我正在构建一个简单的 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>
  )
}

如果有人可以提供帮助,那就太好了。

【问题讨论】:

    标签: javascript reactjs unit-testing jestjs enzyme


    【解决方案1】:

    您正在传递一个带有字符串["New note"] 的数组,但您的代码实际上需要一个带有body 和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>
    

    【讨论】:

      【解决方案2】:

      当然,当您在包装器上找到 div ID 时,您将获得 p 和 button 元素。如果您需要在作为 items 数组传入时断言 p 元素具有文本“New note”。你应该使用这个

      ...
      const textEl = wrapper.find("#text-output p"); // returns p element
      expect(textEl.text()).toBe("New note");
      

      【讨论】:

        猜你喜欢
        • 2018-12-16
        • 1970-01-01
        • 2019-10-26
        • 2019-07-28
        • 1970-01-01
        • 2021-06-24
        • 2021-01-08
        • 2019-12-08
        • 1970-01-01
        相关资源
        最近更新 更多