简体   繁体   中英

Jest test hasClass() method returns false even when it is true

I've been struggling with this for a bit. It basically boils down to checking if the rendered component has a specific class. I've logged it and it only returns true if I call .find() on the specific class I'm searching for. Here is my output:

test('Preview icon to be disabled', () => {
    console.warn(component
      .find('.preview-icon.is-disabled')
      .at(0)
      .html(),
    );

    console.warn(component
      .find('.preview-icon.is-disabled')
      .at(0)
      .hasClass('is-disabled'),
    );

    console.warn(component
      .find('.preview-icon')
      .at(0)
      .html(),
    );

    console.warn(component
      .find('.preview-icon')
      .at(0)
      .hasClass('is-disabled'),
    );

    expect(component
      .find('.preview-icon.is-disabled')
      .at(0)
      .exists(),
    ).toEqual(true);
  });

This outputs:

console.warn client/src/components/Preview.test.js:69
  <span class="toolbar-icon preview-icon is-disabled">Test Component</span>

console.warn client/src/components/Preview.test.js:75
  true

console.warn client/src/components/Preview.test.js:81
  <span class="toolbar-icon preview-icon is-disabled">Test Component</span>

console.warn client/src/components/Preview.test.js:87
  false

My question is, why is my first set of logging true (when I search for .preview-icon.is-disabled ) vs. when I search for only .preview-icon ? The HTML matches, and in the second set of logging HTML it clearly has the class is-disabled .

My actual expect statement is my workaround for it currently, but I feel that there is something I am missing with this test. Any help is greatly appreciated. Thank you.

I genuinely don't have an answer as to why this is happening but I have seen it before and have two potential workarounds that you can try in order to resolve this.

The first workaround centres around your selector of .preview-icon not quite being specific enough. If you were to use span.preview-icon it will more than likely resolve your problem.

The second workaround I'm going to suggest will work if you have used mount to render your component as opposed to shallow . You can use a verification like this to get around the issue:

expect(component.find('.preview-icon').get(0).getDOMNode().classList.contains('is-disabled')).toBeTruthy();

As I said initially, though, I genuinely don't have an exact reason as to why this has happened in your case although, again, it is something I've come across in the past. Hopefully one (or both) of my suggested workarounds will help!

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