【问题标题】:expect(received).toEqual(expected) - errorexpect(received).toEqual(expected) - 错误
【发布时间】:2019-02-04 14:30:05
【问题描述】:

我正在尝试为 React JS 运行单元测试 - 使用 jest / 酶。

目前测试失败。不确定为什么,也许我没有正确调用expect(wrapper.find)。这是我的测试的一部分:

 File.test.js

   it('renders modal when open flag is true', () => {
 const props = { isOpen: true }; 
 const wrapper = mount(
 <div id="root">
  <Component {...props} />
</div>
);
 wrapper.update();
expect(toJson(wrapper)).toMatchSnapshot();
 expect(wrapper.find('.loa-download-header').exists()).toEqual(true);
expect(wrapper.text()).toContain(' Please enter a password.');
 });
 });

这是 File.js 的一部分 显示一段我正在尝试测试的代码作为示例。

 render() {
return (
  <Modal

       <div title="Close Window" className="add-custom-field-close" onClick={() => {this.closeModal()}}><FontAwesome name='xbutton' className='fa-times' /></div>
        </div>
      </div>

      <div className='loa-download-header-wrapper'>
        <div className='loa-download-header'>
          Please enter a password.
          </div>

错误:expect(received).toEqual(expected)

Expected value to equal:
  true
Received:
  false

对代码的任何更正都会非常有帮助,谢谢

【问题讨论】:

  • 您之前是否尝试过删除空格 Please "expect(wrapper.text()).toContain(' Please enter a password.');"?
  • @MadTech 错误指的是这一行:expect(wrapper.find('loa-download-header').exists()).toEqual(true);我确实删除了空间 - 我仍然收到错误
  • 你可以尝试debig它node --inspect-brk node_modules/.bin/jest --runInBandjestjs.io/docs/en/troubleshooting
  • @ChotalaParesh 代码看起来对吗?

标签: reactjs unit-testing jestjs


【解决方案1】:

我花了一些时间将您的代码集成到沙盒中。您的代码有很多更改,我在下面列出了这些更改。我还包括了一些已填写的测试和一些未填写的测试。您应该花一些时间熟悉这些更改,以便您可以在containers/LOAs/__tests__自行填写其余测试。

尽管我为LOAs 容器编写了一个集成测试,但我还是鼓励您为较小的components 编写一个单元测试,这样您就可以练习模拟prop 函数,检查它们是否被调用,并确保组件按预期运行。即使它是多余的,它也会帮助您了解流程、测试什么以及如何测试(对于单元测试,您需要使用 shallowWrap 而不是 mountWrap 函数——或者不要使用它们并使用enzyme提供的shallowmount提供的功能...由您决定。

工作示例https://codesandbox.io/s/p3ro0615nm

变化

  • 创建了一个处理所有UIstate 更改的container 组件
  • 使用this.setState() callbacks 保持state 和辅助操作同步。同样重要的是,这还可以减少不必要的组件闪烁。
  • 使用 conditional rendering 和使用 ternary operator
  • 使用 lodashfiltermapisEmpty 函数(它们很方便,我更喜欢它们而不是原生 JS 函数)
  • 模拟了 2 个 API 调用(注意我使用了 setTimeout,因为这影响您的测试)。在fakeAPI.post 函数中,我添加了一个假密码来检查,因此,提供的密码必须是12345
  • 添加了选择和取消选择 LOA 的功能。如果需要,您可以使用复选框简化所有操作。
  • methodshandle开头,而传递下来的方法以on开头。
  • components/LOAModal/LOAModal.js 分解为更小的/可重复使用的组件,使其更易于阅读
  • 添加了PropType 检查以确保道具在初始声明期间和组件之间保持一致。

注意事项

  • 测试的一个主要部分是了解幕后发生的事情,因此请花时间阅读documentation;并且,如果有必要,做一些更小/更简单的项目来帮助你熟悉 React 的工作原理。
  • 测试时,如果您需要看到 DOMenzyme 看到的一样,那么您可以在 it 测试中看到 console.log(wrapper.debug());
  • 您可以利用beforeEach()函数中的jest.useFakeTimers()afterEach()函数中的jest.runAllTimers()来模拟setTimeout函数,而无需等待实时通过。
  • 非常重要:始终在Promise(API 调用)之后包含.catch()。如果您不 catch 您的 Promise,那么它可能会导致您的应用崩溃。

【讨论】:

  • 非常感谢。我一定会看看你做了什么。你们提供辅导吗?
  • 我没有。但是,如果您愿意投入一些时间和一点钱,那么我建议您投资这个在线课程:udemy.com/react-2nd-edition
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-08
  • 2018-10-25
  • 1970-01-01
  • 2018-09-03
  • 1970-01-01
相关资源
最近更新 更多