My app is slightly unusual in that the appearance is actually critically important. It's sort of a photo manipulation app, so I want to be able to write tests to check, for example, that an element actually has a particular background color. I'm able to find elements with react-testing-library but my jest .toHaveStyle() assertions seem to always pass.
The element under test (rest of component omitted)
<span
className="swatch"
style={{ background: `#${colorToString(color)}` }}
aria-label="original color"
/>
The test
describe('BeadMapRow', () => {
let result: RenderResult;
beforeEach(() => {
const bead = {
brand: 'Test',
code: 'T01',
name: 'Test Bead 1',
color: 0x005080ff
};
result = render(<BeadMapRow color={0x084a8bff} bead={bead} />);
});
it('works', () => {
const e = result.getByLabelText('original color');
console.log(e);
expect(e).toHaveStyle({ 'background-color': '0x084a8bff' });
});
});
Result of that console.log (trimmed)
console.log src/components/beadMapRow.test.tsx:21
HTMLSpanElement {
'__reactInternalInstance$a7if3tsd8xg':
FiberNode {
tag: 5,
key: null,
elementType: 'span',
type: 'span',
stateNode: [Circular],
return:
FiberNode {
/* ... */
},
child: null,
sibling:
FiberNode {
/*...*/
},
index: 0,
ref: null,
pendingProps:
{ className: 'swatch',
style: [Object],
'aria-label': 'original color' },
memoizedProps:
{ className: 'swatch',
style: [Object],
'aria-label': 'original color' },
/* ... */
'__reactEventHandlers$a7if3tsd8xg':
{ className: 'swatch',
style: { background: '#084a8bff' },
'aria-label': 'original color' },
[Symbol(SameObject caches)]:
[Object: null prototype] {
style:
CSSStyleDeclaration {
_values: {},
_importants: {},
_length: 0,
_onChange: [Function] },
childNodes: NodeList {} } }
If I change the expected color to something else, it still passes. The only way so far I've found to make it fail is to say .toHaveStyle('background-color') without a value.