Skip to content

Commit dcbfc3b

Browse files
authored
Update using workerize-loader within Jest tests
See #103 Existing guide on how to make `workerize-loader` working with Webpack and Jest wasn't sufficient. I tried given steps in my project and everything seems working as expected 😄
1 parent 111e17a commit dcbfc3b

File tree

1 file changed

+20
-15
lines changed

1 file changed

+20
-15
lines changed

README.md

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ All worker code can now use Promises.
105105

106106
### Testing
107107

108+
## Without Webpack
108109
To test a module that is normally imported via `workerize-loader` when not using Webpack, import the module directly in your test:
109110

110111
```diff
@@ -113,24 +114,28 @@ To test a module that is normally imported via `workerize-loader` when not using
113114

114115
const instance = worker();
115116
```
116-
117-
To test modules that rely on workerized imports when not using Webpack, you'll need to dig into your test runner a bit. For Jest, it's possible to define a custom `transform` that emulates workerize-loader on the main thread:
118-
119-
```js
120-
// in your Jest configuration
121-
{
122-
"transform": {
123-
"workerize-loader(\\?.*)?!(.*)": "<rootDir>/workerize-jest.js"
124-
}
125-
}
117+
## With Webpack and Jest
118+
In Jest, it's possible to define a custom `transform` that emulates workerize-loader on the main thread.
119+
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"
126125
```
127-
128-
... then add the `workerize-jest.js` shim to your project:
129-
130-
```js
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+
}
133+
```
134+
4. Add jest custom transformer file `workerize-jest.js` in root dir:
135+
```ts
131136
module.exports = {
132137
process(src, filename, config, options) {
133-
return 'module.exports = () => require(' + JSON.stringify(filename.replace(/.+!/,'')) + ')';
138+
return 'module.exports = () => require(' + JSON.stringify(filename.replace(/.+!/, '')) + ')';
134139
},
135140
};
136141
```

0 commit comments

Comments
 (0)