I need to test styles of a component from sass, but only inline styles are loaded in the dom
my test case:
describe('Danger', () => {
const dangerLabel = <DangerLabel>TESTE</DangerLabel>;
it('deve ter class -danger', () => {
const { container } = render(dangerLabel);
expect(container.firstChild).toHaveClass('-danger');
});
it('deve ter a cor vermelho', () => {
const { container } = render(dangerLabel);
const style = window.getComputedStyle(container.firstElementChild);
expect(style.backgroundColor).toBe('#e74c3c');
});
});
jest-config
module.exports = {
roots: ['<rootDir>'],
transform: {
'\\.(js|jsx)?$': 'babel-jest',
},
testMatch: [
'<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}',
],
moduleFileExtensions: ['js', 'jsx', 'json', 'node'],
testPathIgnorePatterns: ['/node_modules/', '/public/'],
setupFilesAfterEnv: [
'@testing-library/jest-dom/extend-expect',
],
moduleNameMapper: {
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '<rootDir>/config/jest/__mocks__/fileMock.js',
'.+\\.(css|scss)$': 'identity-obj-proxy',
},
};
component export:
import LabelContainer from './label_container';
import Label from './DefaultLabel';
import DangerLabel from './DangerLabel';
import PrimaryLabel from './PrimaryLabel';
import WarningLabel from './WarningLabel';
import SuccessLabel from './SuccessLabel';
import InfoLabel from './InfoLabel';
import '../assets/styles/label.scss';
export default Label;
export {
LabelContainer,
PrimaryLabel,
DangerLabel,
WarningLabel,
SuccessLabel,
InfoLabel,
};
exec:
expect(received).toBe(expected) // Object.is equality
Expected: "#e74c3c"
Received: ""
30 | const { container } = render(dangerLabel);
31 | const style = window.getComputedStyle(container.firstElementChild);
> 32 | expect(style.backgroundColor).toBe('#e74c3c');
| ^
33 | });
34 | });
35 |
I have tried some packages like jest-transform-css and jest-transform-scss but with no success, it is possible to do that test?
As requested DangerLabel Code:
import React from 'react';
import DefaultLabel from './DefaultLabel';
const DangerLabel = props => (
<DefaultLabel {...props} className="-danger" />
);
export default DangerLabel;
With toHaveStyle:
it('deve ter a cor vermelho', () => {
const { container } = render(dangerLabel);
expect(container.firstElementChild).toHaveStyle(`
background-color: rgb(231, 76, 60)};
`);
});
Result: