What is identity-obj-proxy?
The identity-obj-proxy package is primarily used for mocking module exports in JavaScript tests. It's especially useful when working with CSS Modules in a Jest testing environment, as it allows you to proxy the imported CSS Modules with an identity object that returns the module's name for any property access. This way, tests can be run without having to worry about the actual CSS and focus on the JavaScript logic.
What are identity-obj-proxy's main functionalities?
Mocking CSS Modules in Jest
This code snippet demonstrates how to mock a CSS module import using identity-obj-proxy in a Jest test. It replaces the actual styles with an object that has the same keys as the class names defined in the CSS file, but with values equal to the keys themselves.
jest.mock('styles.module.css', () => require('identity-obj-proxy'));
Other packages similar to identity-obj-proxy
proxyquire
proxyquire is a package that allows you to override dependencies during testing. It is similar to identity-obj-proxy in that it helps with mocking modules, but it is more general-purpose and can be used to proxy any module, not just CSS modules. It provides more control over the mocking behavior compared to identity-obj-proxy.
identity-obj-proxy
An identity object using ES6 proxies. Useful for testing trivial webpack imports. For instance, you can tell Jest to mock this object as imported CSS modules; then all your className
lookups on the imported styles
object will be returned as-is.
npm install identity-obj-proxy
Requirement
No flag is required for Node.js v6.*
; use node --harmony_proxies
flag for v5.*
and v4.*
.
Example
import idObj from 'identity-obj-proxy';
console.log(idObj.foo);
console.log(idObj.bar);
console.log(idObj[1]);