当预期失败时,使用"toHaveStyle"进行测试通过



我正在学习测试和反应。我有点难以理解为什么一个测试通过了,而它不应该通过:

从App.js

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

从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  

关于项目的更多信息:

"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"
}
有人能帮我一下吗?

看起来在这种情况下用Object测试toHaveStyle会导致错误,我真的不知道为什么。你可能应该在test -library/jest-dom github中打开一个issue。

但是现在,如果你使用一个简单的字符串来测试背景应该可以工作,就像这样:

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

和完整的测试:

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");
});

您可以在这里查看toHaveStyle的其他选项。

最新更新