I got this question when I was testing a React component with Jest, and Jest yelled at me that it could not deal with the imported CSS module (which is managed by webpack). The problem was solved with object-identity-proxy
.
Here’s the description of object-identity-proxy
from their npm page:
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.
So what is an ES6 proxy?
Here’s what MDN says:
The Proxy object is used to define custom behavior for fundamental operations (e.g. property lookup, assignment, enumeration, function invocation, etc).
Syntax
1 | const p = new Proxy(target, handler) |
Parameters
target
:
A target object to wrap with Proxy. It can be any sort of object, including a native array, a function, or even another proxy.handler
:
An object whose properties are functions define the behavior of proxy p when an operation is performed on it.
Operations that could be trapped with handler
MDN listed all the handler object methods, i.e. fundamental operations that could be traps by handler:
handler.getPrototypeOf()
A trap for Object.getPrototypeOf.handler.setPrototypeOf()
A trap for Object.setPrototypeOf.handler.isExtensible()
A trap for Object.isExtensible.handler.preventExtensions()
A trap for Object.preventExtensions.handler.getOwnPropertyDescriptor()
A trap for Object.getOwnPropertyDescriptor.handler.defineProperty()
A trap for Object.defineProperty.handler.has()
A trap for the in operator.handler.get()
A trap for getting property values.handler.set()
A trap for setting property values.handler.deleteProperty()
A trap for the delete operator.handler.ownKeys()
A trap for Object.getOwnPropertyNames and Object.getOwnPropertySymbols.handler.apply()
A trap for a function call.handler.construct()
A trap for thenew
operator.
Now check the object-identity-proxy
Here’s the code I found in node_modules/identity-obj-proxy/src/index.js
:
1 | idObj = new Proxy({}, { |
So this is what they mean by ‘returned as-is’!
Write my first two simple proxies
Now I’ll write two simple proxies to practice.
Default Dictionary
1 | const myDictionary={dog: "woof", cat:"meow", duck:"quack"}; |
Now I can get and set the animal sounds:
1 | console.log(myDefaultDictionary.cat); //'meow' |
Check on argument
1 | function getALuckyNumber(name) { |
Now I always get a fixed lucky number (and get told off when I ask it):
1 | getLuckyNumberAnranMachine("yihao"); // yihao's lucky number is 12 |
A nice extending constructor example by MDN
1 | function extend(sup, base) { |
Next Step
Haven’t fully understand the MDN extending constructor example yet:
What is Object.getOwnPropertyDescriptor
? How to best understand what is proptype
in JavaScript?