Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update using workerize-loader within Jest tests #107

Merged
merged 4 commits into from
Jan 9, 2021
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 20 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ All worker code can now use Promises.

### Testing

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

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

const instance = worker();
```

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:

```js
// in your Jest configuration
{
"transform": {
"workerize-loader(\\?.*)?!(.*)": "<rootDir>/workerize-jest.js"
}
}
## With Webpack and Jest
In Jest, it's possible to define a custom `transform` that emulates workerize-loader on the main thread.

Steps to follow:
1. Install dev dependencies `npm i babel-jest identity-object-proxy -D`
2. Add this entry to `moduleNameMapper` section in jest config located in `package.json`:
```ts
"workerize-loader(\\?.*)?!(.*)": "identity-obj-proxy"
```

... then add the `workerize-jest.js` shim to your project:

```js
3. Add this entry to jest config located in `package.json`:
```ts
"transform": {
"workerize-loader(\\?.*)?!(.*)": "<rootDir>/workerize-jest.js",
"^.+\\.[jt]sx?$": "babel-jest",
"^.+\\.[jt]s?$": "babel-jest"
}
```
4. Add jest custom transformer file `workerize-jest.js` in root dir:
```ts
module.exports = {
process(src, filename, config, options) {
return 'module.exports = () => require(' + JSON.stringify(filename.replace(/.+!/,'')) + ')';
return 'module.exports = () => require(' + JSON.stringify(filename.replace(/.+!/, '')) + ')';
},
};
```
Expand Down