Himanshu
Himanshu

Reputation: 573

Testing component created using styled component with jest and enzyme

I have a few tags created using styled components lib:

component.js

....
const NoJobs = styled.h1`
    text-align: center;
`;
....
<div>
  <NoJobs>
    No Jobs Found!!!
  </NoJobs>
</div>

I want to test this component, below is my test case:

component.test.js

describe('<JobList />', () => {
    let wrapper;

    beforeEach(() => {
        wrapper = shallow(<JobList />);
    });

    it('should show "no data found" when there is no data', () => {
       expect(wrapper.contains(<NoJobs>No Jobs Found!!!</NoJobs>)).toEqual(true);
    });
});

When I run above test it show: NoJobs is not defined.

Though if I change NoJobs with plan div tag in both component.js and component.test.js, it works fine. How can I test tags created using styled-components?

Upvotes: 1

Views: 6885

Answers (1)

skyboyer
skyboyer

Reputation: 23705

Quick way

You may export NoJobs like

const NoJobs = styled.h1`...

And that will work. Also you may use find() that may take a displayName string, so you can

const NoJobs = styled.h1`...
NoJobs.displayName = "NoJobs";

and then in test:

expect(wrapper.find('NoJobs').text()).toEqual("No Jobs Found!!!");

Also you can install special babel plugin to handle that automatically.

Systematic approach

But to me most maintainable way is avoid sticking to dislayname/component name at all and use attribute-based selectors:

<div>
  <NoJobs data-testid="no-jobs-message">
    No Jobs Found!!!
  </NoJobs>
</div>

and later in test

expect(wrapper.find({"data-testid": "no-jobs-message"}).text()).toEqual("No Jobs Found!!!")

Upvotes: 2

Related Questions