get HTML element style in react enzyme unit test
get HTML element style in react enzyme unit test
I am trying to write a unit test in react with enzyme. You can see the test code below.
describe("When list page is opened", () => {
let wrapper;
beforeAll(() =>
wrapper = mount(<PersonList ...data/>);
);
it('should have grey background color', () =>
console.log(wrapper.find('div.profile-card').props().style);
expect(wrapper.find('div.profile-card').props().style.backgroundColor).toBe('red');
);
I have set a background color to the HTML element and I am trying to validate the element has the right color. But style value is undefined and I could not reach the background.
The error message:
TypeError: Cannot read property 'backgroundColor' of undefined
I could not understand what is wrong. When I check the backgroundColor of the element with chrome developer tools, I could see that there is a background value.
What might cause the problem? I would appreciate if you share your comments!
thanks in advance!
P.S. : I realized that when I used inline style, it worked! So I am curious how can I test the style in a css file! If it is not possible to tests in the css file, maybe I should avoid defining styles in a seperate css files. What is the best practice to manage style is React?
props().style backgroundColor
props().backgroundColor
@karl you are right, while I was experimenting I mistakenly delete style. I fixed it, but the problem still continue. I will fix the question.
– wasabi
Sep 15 '18 at 15:28
To look at the actual DOM structure you are working with, do a
console.log(wrapper.debug());
. Maybe you can figure out what is wrong then.– karl
Sep 15 '18 at 15:31
console.log(wrapper.debug());
@karl, I set style in a seperate css file. I suspect that enzyme tests do not use external css files, they only render inline style. It might be the reason of the problem? Do you know that enzyme use the external style files or not??
– wasabi
Sep 15 '18 at 15:47
@karl, when I use inline style in js file, it worked! Is there any way to test the style which is defined in a separate css file?
– wasabi
Sep 15 '18 at 15:57
0
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy
Aren't you supposed to expect on
props().style backgroundColor
and notprops().backgroundColor
?– karl
Sep 15 '18 at 15:26