繁体   English   中英

使用 Chai 和 Jest 测试“HTMLElement”DOM 元素时出错

[英]Error using Chai and Jest to test `HTMLElement` DOM elements

假设我有一个非常简单的组件,它接受一些props并为无效的 state 呈现一个简单的<div>

// InvalidState.js
// Renders an "Invalid" state display

const render = (props = {}) => {

  // Create the <div> element

  let div = document.createElement('div');
  div.classList.add('my-component');
  div.classList.add('my-component--invalid');

  div.innerHTML = props.message;

  return div;
};

export { render };

我使用 Jest 作为测试运行程序,使用chai作为期望/断言库。

为了测试我试过的上述内容;

// InvalidState.test.js

import { expect } from 'chai';
import * as InvalidState from './InvalidState';

let wrapper;

describe('<InvalidState />', () => {

  it('renders the component', () => {
    // Call to `render()` returns an HTMLElement
    // (Specifcally, a HTMLDivElement)
    wrapper = InvalidState.render({ message: 'some message' });

    // Find an element by class name
    const invalid = wrapper.getElementsByClassName('.my-component--invalid')[0];

    // Test its contents
    expect(invalid).to.have.text('some message');
  });

});

但是我得到了错误

expect(invalid).to.have.text(InvalidState.DEFAULT_MESSAGE);
^

Invalid Chai property: text. Did you mean "that"?
  1. chai 和 jest 是我在测试 HTML 元素时应该使用的正确库吗? 还是有更好的选择?

  2. 为什么上面的text()方法不能正确执行?

谢谢!

我发现text()仅适用于chai-jquery 或者至少这就是这个备忘单所说的: https://devhints.io/chai

我将其修改为使用innerText并且效果很好

div.innerText = props.message;
expect(wrapper.innerText.eql(InvalidState.DEFAULT_MESSAGE);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM