Skip to content

Commit 0471010

Browse files
authored
Improve transformer to accurately return async functions
1 parent dcbfc3b commit 0471010

File tree

1 file changed

+38
-18
lines changed

1 file changed

+38
-18
lines changed

README.md

Lines changed: 38 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -114,33 +114,53 @@ To test a module that is normally imported via `workerize-loader` when not using
114114

115115
const instance = worker();
116116
```
117+
117118
## With Webpack and Jest
119+
118120
In Jest, it's possible to define a custom `transform` that emulates workerize-loader on the main thread.
119121

120-
Steps to follow:
121-
1. Install dev dependencies `npm i babel-jest identity-object-proxy -D`
122-
2. Add this entry to `moduleNameMapper` section in jest config located in `package.json`:
123-
```ts
124-
"workerize-loader(\\?.*)?!(.*)": "identity-obj-proxy"
122+
First, install `babel-jest` and `identity-object-proxy`:
123+
124+
```sh
125+
npm i -D babel-jest identity-object-proxy
125126
```
126-
3. Add this entry to jest config located in `package.json`:
127-
```ts
128-
"transform": {
129-
"workerize-loader(\\?.*)?!(.*)": "<rootDir>/workerize-jest.js",
130-
"^.+\\.[jt]sx?$": "babel-jest",
131-
"^.+\\.[jt]s?$": "babel-jest"
132-
}
127+
128+
Then, add these properties to the `"transform"` and `"moduleNameMapper"` sections of your Jest config (generally located in your `package.json`):
129+
130+
```js
131+
{
132+
"jest": {
133+
"moduleNameMapper": {
134+
"workerize-loader(\\?.*)?!(.*)": "identity-obj-proxy"
135+
},
136+
"transform": {
137+
"workerize-loader(\\?.*)?!(.*)": "<rootDir>/workerize-jest.js",
138+
"^.+\\.[jt]sx?$": "babel-jest",
139+
"^.+\\.[jt]s?$": "babel-jest"
140+
}
141+
}
142+
}
133143
```
134-
4. Add jest custom transformer file `workerize-jest.js` in root dir:
135-
```ts
144+
145+
Finally, create the custom Jest transformer referenced above as a file `workerize-jest.js` in your project's root directory (where the package.json is):
146+
147+
```js
136148
module.exports = {
137-
process(src, filename, config, options) {
138-
return 'module.exports = () => require(' + JSON.stringify(filename.replace(/.+!/, '')) + ')';
139-
},
149+
process(src, filename) {
150+
return `
151+
async function asyncify() { return this.apply(null, arguments); }
152+
module.exports = function() {
153+
const w = require(${JSON.stringify(filename.replace(/^.+!/, ''))});
154+
const m = {};
155+
for (let i in w) m[i] = asyncify.bind(w[i]);
156+
return m;
157+
};
158+
`;
159+
}
140160
};
141161
```
142162

143-
Now your tests and any modules they import can use `workerize-loader!` prefixes.
163+
Now your tests and any modules they import can use `workerize-loader!` prefixes, and the imports will be turned into async functions just like they are in Workerize.
144164

145165
### Credit
146166

0 commit comments

Comments
 (0)