简体   繁体   中英

Error using Chai and Jest to test `HTMLElement` DOM elements

Say I have a very simple component that takes in some props and renders a simple <div> for an invalid state:

// 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 };

I'm using Jest as a test runner and chai as an expectations/assertions library.

To test the above I tried;

// 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');
  });

});

However I get the error

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

Invalid Chai property: text. Did you mean "that"?
  1. Are chai and jest the right libraries that I should use in testing HTML elements? Or is there a better alternative?

  2. Why would the text() method above not execute correctly?

Thanks!

I discovered that text() only works with chai-jquery . Or at least that's what this cheatsheet says: https://devhints.io/chai

I revised it to use innerText and it worked fine

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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