我正在参与一个使用Typescript作为前端的mvc.net项目。
module Foo {...}
包装了许多打字稿文件,其中
Foo是主要模块或名称空间。
所有打字稿文件都转换为一个文件Foo.js
。
问题是没有任何打字稿文件具有export module Foo{...}
来导出名称空间。
我想为此编写一个单元测试,并且选择了Jest框架。
如何在测试中导入打字稿文件中的对象。
package.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未定义
答案 0 :(得分:0)
为我工作。顺便说一句:
内部“模块”语法已过时,请改用“名称空间”关键字。
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