Home > Back-end >  Testing with 'toHaveStyle' passes when expecting fail
Testing with 'toHaveStyle' passes when expecting fail

Time:05-20

I'm learning about testing and react. I'm having a little trouble understanding why a test is passing when it should not:

From App.js

      <button style={{backgroundColor: 'gray'}}>
        Gray button
      </button>

From App.test.js

    expect(colorButton).toHaveStyle( {backgroundColor: 'gray' }); // passes ok
    expect(colorButton).toHaveStyle( {backgroundColor: 'fay' }); // passes but should not
    expect(colorButton).toHaveStyle( {backgroundColor: 'dfhdhsdh' }); // passes but should not
    expect(colorButton).toHaveStyle( {backgroundColor: 'red' }); // expected error
    expect(colorButton).toHaveStyle( {backgroundColor: 'MidnightBlue' }); // expected error  

More info about the project:

      "dependencies": {
        "@testing-library/jest-dom": "^5.16.4",
        "@testing-library/react": "^13.2.0",
        "@testing-library/user-event": "^13.5.0",
        "react": "^18.1.0",
        "react-dom": "^18.1.0",
        "react-scripts": "5.0.1", 
        "web-vitals": "^2.1.4"
      }

Could anyone help me, please?

CodePudding user response:

Looks like testing toHaveStyle with an Object in this case is causing an error and i really don´t know why. You should probably open an issue in testing-library/jest-dom github.

But for now, if you use a simple string to test the background should work, just like that:

expect(colorButton).toHaveStyle("background-color: gray");

and the complete test:

test("background test", () => {
    const { getByRole, debug } = render(<App />);
 
    // To check what jest-dom is rendered, debug is always a good idea.
    // And here you will see that button is rendering with style="background-color: gray;"
    debug();

    const colorButton = getByRole("button");

    expect(colorButton).toHaveStyle("background-color: gray");
    expect(colorButton).not.toHaveStyle("background-color: fay");
    expect(colorButton).not.toHaveStyle("background-color: dfhdhsdh");
    expect(colorButton).not.toHaveStyle("background-color: red");
  });

You can check other options of toHaveStyle here.

  • Related