Typescript / Jest无法识别Web Worker

时间:2019-12-26 12:53:52

标签: javascript typescript jestjs web-worker

我正在尝试将Web Workers与Typescript一起使用。我有一个具有以下结构的项目:

__tests__
|
| test.ts
--- 
src
|
| something.ts
| someelse.ts
--- 
jest.config.js
package.json
tsconfig.json

tsconfig.json

{ 
  "compileOnSave": true,
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es6",
    "noImplicitAny": false,
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "dist",
    "baseUrl": ".",
    "lib": ["webworker", "es2015", "scripthost"]
  },
  "exclude": [
    "node_modules"
  ]
}

package.json

{
  "name": "test-ts",
  "version": "1.0.0",
  "main": "main.ts",
  "scripts": {
    "test": "jest"
  },
  "author": "",
  "dependencies": {
    "@types/node": "^13.1.0",
    "awesome-typescript-loader": "^5.2.1",
    "typescript": "^3.7.4",
    "webpack": "^4.41.4",
    "worker-loader": "^2.0.0"
  },
  "devDependencies": {
    "@types/jest": "^24.0.24",
    "jest": "^24.9.0",
    "ts-jest": "^24.2.0"
  }
}

jest.config.js

module.exports = {
  "roots": [
    "<rootDir>"
  ],
  "testMatch": [
    "**/__tests__/**/*.+(ts|tsx|js)",
    "**/?(*.)+(spec|test).+(ts|tsx|js)"
  ],
  "transform": {
    "^.+\\.(ts|tsx)$": "ts-jest"
  },
}

IDE可以很好地识别Worker类,但是我无法运行任何Jest测试。程序尝试实例化Worker类的成员时出现错误:

$> npm test

> test-ts@1.0.0 test $
> jest

 FAIL  __tests__/tests.ts
  × basic (3ms)

  ● basic

    ReferenceError: Worker is not defined

       9 |   receiveUpdate(id: string, shipmentData: any) {
      10 |     if (!this.idToWorker[id]) {
    > 11 |       const worker = new Worker('worker.ts');
         |                      ^
      12 |       this.idToWorker[id] = { worker, processed: [] };
      13 |       const _idToWorker = this.idToWorker[id];
      14 |       this.idToWorker[id].worker.addEventListener("message", message => {

      at ShipmentUpdateListener.receiveUpdate (src/listener.ts:11:22)
      at Object.<anonymous>.test (__tests__/tests.ts:5:12)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        3.99s
Ran all test suites.
npm ERR! Test failed.  See above for more details.

出什么问题了?有没有办法将Jest将TS转换为JavaScript,以便它可以识别Worker类?

谢谢。

0 个答案:

没有答案