Testing component created using styled component with jest and enzyme

微笑、不失礼 提交于 2021-02-11 18:16:10

问题


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?


回答1:


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!!!")


来源:https://stackoverflow.com/questions/59503501/testing-component-created-using-styled-component-with-jest-and-enzyme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!