首页 > 解决方案 > 模块或命名空间中打字稿文件的 Jest 单元测试

问题描述

我正在参与一个使用 typescript 作为前端的 mvc.net 项目。有许多用 包裹的打字稿文件module Foo {...},其中 Foo 是主模块或命名空间。

所有的打字稿文件都被转换成一个文件Foo.js。问题是没有任何打字稿文件必须export module Foo{...}导出命名空间。我想为此编写一个单元测试,我选择了 Jest 框架。

如何在我的测试中导入我的打字稿文件中的对象。

包.json

{
  "version": "1.0.0",
  "name": "Foo-Web",
  "private": true,
  "devDependencies": {
    "@types/bootstrap": "4.1.2",
    "@types/jquery": "^3.3.16",
    ... bunch of other libraries
  },
  "scripts": {
    "test": "jest"
  }
}

tsconfig.json

{
  "compileOnSave": true,
  "compilerOptions": {
    "isolatedModules": false,
    "allowSyntheticDefaultImports": true,
    "jsx": "react",
    "lib": [
      "dom",
      "es2017"
    ],
    "noImplicitAny": false,
    "noEmitOnError": true,
    "outFile": "Out/dist/Foo.js",
    "removeComments": true,
    "sourceMap": true,
    "target": "es5"
  },
  "exclude": [
    "**/bower_components/*",
    "**/node_modules/*",
    "**/dist/*"
  ],
}

jest.config.js

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

打字稿文件的格式就像

module Foo {
    interface blablabla ....

    export class hahaha{
     ... class implementation
    }
}

测试文件:

...
var ct = new Foo.SomeClass(testProp)
....

运行笑话测试,我收到:

Foo 未定义

标签: typescriptunit-testingjestjs

解决方案


为我工作。顺便提一句:

不推荐使用内部“模块”语法,请改用“命名空间”关键字。

index.ts

export module Foo {
  export class SomeClass {
    constructor(private prop) {}
  }
}

index.test.ts

import { Foo } from './';

describe('63957901', () => {
  it('should pass', () => {
    const testProp = {};
    const ct = new Foo.SomeClass(testProp);
    expect(ct).toBeInstanceOf(Foo.SomeClass);
  });
});

单元测试结果:

 PASS  src/stackoverflow/63957901/index.test.ts (10.923s)
  63957901
    ✓ should pass (4ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        12.401s

推荐阅读