-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Description
@testing-library/react
version:11.1.2
- Testing Framework and version: jest
26.6.3
- DOM Environment: jsdom
16.4.0
Relevant code or config:
File mock that unexpectedly renders with no className
:
Jest config:
// jest.config.js
module.exports = {
moduleNameMapper: {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
"<rootDir>/__mocks__/file-mock.js",
},
};
// __mocks__/file-mock.js
// See Jest docs: https://jestjs.io/docs/en/webpack.html#handling-static-assets
module.exports = 'test-file-stub';
Variants that successfully render className
:
module.exports = 'div';
module.exports = 'testFileStub';
(works but React emits warning about case)module.exports = 'TestFileStub';
(works but React emits warning)
What you did:
Rendered a component using a file stub mock, in this case an SVG:
// Icon.js - component definition
import React from "react";
import Icon from "./icon.svg";
const Logo = () => {
return <Icon className="myLogo" />;
};
export default Logo;
Test that checks for the className
:
// Icon.test.js - component test
import React from "react";
import { render } from "@testing-library/react";
import Icon from "./Icon";
test("has a className", () => {
const { container } = render(<Icon />);
expect(container.firstChild.className).toBe("myLogo");
});
What happened:
className
is unexpectedly en empty string ""
when the file mock exports a kebab case string test-file-stub
, but works correctly when it's not kebab case.
Reproduction:
I've added reduced cases in a repo: https://github.com/davidcalhoun/jest-bug-test-file-stub
The issue with the kebab case can be seen here: https://github.com/davidcalhoun/jest-bug-test-file-stub/tree/main/kebab-not-working
Here's a workaround by changing test-file-stub
to div
: https://github.com/davidcalhoun/jest-bug-test-file-stub/tree/main/working
Problem description:
The Jest docs recommend using test-file-stub
as a file mock, but this results in an element that's unexpectedly output with no className
. This issue doesn't occur when using a similar test with react-test-renderer
, which doesn't use jsdom
. This may turn out to be some underlying issue with jsdom
? Or maybe something I'm missing.
Thank you in advance!
Suggested solution:
Workaround for file mocking:
// __mocks__/file-mock.js
// See https://jestjs.io/docs/en/webpack.html#handling-static-assets
-module.exports = 'test-file-stub';
+module.exports = 'div';