What is jest-transform-stub?
The jest-transform-stub package is a Jest transformer that returns an empty object for various file types. This is useful for stubbing out non-JavaScript files (like CSS, images, etc.) in your tests, allowing you to focus on testing JavaScript code without worrying about these assets.
What are jest-transform-stub's main functionalities?
Stub CSS files
This feature allows you to stub out CSS files in your Jest tests. When Jest encounters a CSS file, it will return an empty object, preventing errors related to missing styles.
module.exports = {};
Stub image files
This feature allows you to stub out image files (like PNG, JPG, etc.) in your Jest tests. When Jest encounters an image file, it will return an empty object, preventing errors related to missing images.
module.exports = {};
Stub other file types
This feature allows you to stub out other file types (like SVG, JSON, etc.) in your Jest tests. When Jest encounters these file types, it will return an empty object, preventing errors related to missing assets.
module.exports = {};
Other packages similar to jest-transform-stub
identity-obj-proxy
The identity-obj-proxy package is a Jest transformer that returns a proxy object for CSS modules. This allows you to mock CSS modules in your tests, providing a more realistic representation of the CSS classes. Unlike jest-transform-stub, which returns an empty object, identity-obj-proxy returns an object with keys corresponding to the CSS class names.
jest-css-modules
The jest-css-modules package is a Jest transformer that mocks CSS modules by returning a simple object with class names as keys. This is similar to jest-transform-stub but provides a more detailed mock of CSS modules, making it easier to test components that rely on specific class names.
jest-transform-css
The jest-transform-css package is a Jest transformer that converts CSS files into JavaScript objects. This allows you to import CSS files in your tests and access the styles as JavaScript objects. Unlike jest-transform-stub, which returns an empty object, jest-transform-css provides a more detailed representation of the CSS styles.
jest-transform-stub
Jest doesn't handle non JavaScript assets by default.
You can use this module to avoid errors when importing non JavaScript assets.
Usage
npm install --save-dev jest-transform-stub
In your Jest config, add jest-transform-stub to transform non JavaScript assets you want to stub:
{
"jest": {
"transform": {
"^.+\\.js$": "babel-jest",
".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "jest-transform-stub"
}
}
}
FAQ
My module isn't being transformed
Jest doesn't apply transforms to node_modules by default. You can solve this by using moduleNameMapper
:
{
"jest": {
"moduleNameMapper": {
"^.+.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "jest-transform-stub"
}
}
}