Reputation: 355
I'm using css modules in my react project and using web pack for bundling. While using Jest for testing, as the jest will try to import css files like normal JS files got the below error,
SyntaxError: Unexpected token .
The solution that I found is to use "identity-obj-proxy" to mock scss/css files.But now I cannot use css selectors to test components.For example
it('renders 2 children', () => {
expect(component.find('.mockyApp').children().length).toBe(2);
});
render() {
if (this.state.host) {
return (
<div className={style.mockyApp}>
<div className={style.sidePage}>
<SideBar clickHandler={this.setPage} selected={this.state.page}/>
</div>
<div className={style.mainPage}>
{this.renderComponent()}
</div>
</div>
);
}
// ... .. rest of render method
}
I'm using import style from './mocky.scss'; to import styles and using the style object for class names. Before using css-modules the above test used to work.Now my question is how will I be able to test using css selectors and what change needs to be done to make this work?. Googling didn't help
Upvotes: 3
Views: 10147
Reputation: 53229
I don't think there exists a good solution for this problem yet.
Few ways you can still test it:
1) Add a static class name just for testing:
<div className={`${style.mockyApp} mockyApp`}>
<div className={style.sidePage}>
<SideBar clickHandler={this.setPage} selected={this.state.page}/>
</div>
<div className={style.mainPage}>
{this.renderComponent()}
</div>
</div>
2) Use a data attribute to target that element.
Component
<div className={`${style.mockyApp} mockyApp`} data-jest="mockyApp">
<div className={style.sidePage}>
<SideBar clickHandler={this.setPage} selected={this.state.page}/>
</div>
<div className={style.mainPage}>
{this.renderComponent()}
</div>
</div>
Render
it('renders 2 children', () => {
expect(component.find('[data-jest=mockyApp]').children().length).toBe(2);
});
Both ways work but they include adding stuff to the DOM which gets shipped to production, which means more bytes being sent to your users.
If you are going with the second approach, you can consider writing a Babel plugin that strips out all data-jest
attributes from the DOM in the transpilation process.
Upvotes: 4