【发布时间】:2016-10-19 14:36:27
【问题描述】:
我正在尝试使用 Jasmine 在 Typescript 中编写单元测试并使用 Karma 运行。我已经阅读了this tutorial 并看到了关于 SO 的this 问题,但我的问题仍然存在。
当 Typescript 编译器将我的 typescript 编译成 javascript 时,它使用 require 语法从其他文件导入定义。当我运行我编译的测试时,我得到一个类似于这个的错误:
Uncaught ReferenceError: require is not defined
at calculator.spec.js
据此,我推测在执行我的规范时没有任何可以定义require 语法的内容。但是,我不清楚我应该怎么做。一个 SO 问题建议使用 karma-browserify,但我注意到上面的教程在没有它的情况下设法让它工作。任何人都可以提供任何帮助,我们将不胜感激。
这是我的文件:
package.json
{
"name": "karma-stuff",
"version": "0.1.0",
"description": "A thing that helps me test stuff",
"main": "index.js",
"scripts": {
"test": "karma start"
},
"keywords": [
"help"
],
"author": "me",
"license": "MIT",
"devDependencies": {
"jasmine": "^2.5.2",
"karma": "^1.3.0",
"karma-chrome-launcher": "^2.0.0",
"karma-jasmine": "^1.0.2",
"karma-typescript-preprocessor": "^0.3.0",
"tsc": "^1.20150623.0"
}
}
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
}
}
typings.json
{
"globalDependencies": {
"core-js": "registry:dt/core-js#0.0.0+20160725163759",
"jasmine": "registry:dt/jasmine#2.5.0+20161003201800",
"node": "registry:dt/node#6.0.0+20160909174046"
}
}
karma.conf.js
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'*.spec.ts'
],
preprocessors: {
'**/*.ts': ['typescript']
},
typescriptPreprocessor: {
options: {
sourceMap: true, // generate source maps
noResolve: false // enforce type resolution
},
transformPath: function(path) {
return path.replace(/\.ts$/, '.js');
}
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
concurrency: Infinity
})
}
被测对象:calculator.service.ts
export class Calculator {
add(a: number, b: number): number {
return a + b;
}
}
测试自身:calculator.spec.ts
import { Calculator } from './calculator.service';
describe("A calculator", function() {
it("adds integers correctly", function() {
let things = new Calculator();
expect(things.add(1, 2)).toBe(3);
});
});
【问题讨论】:
-
您介意在 plunkr 上分享您的文件以了解您的项目结构吗?
-
您引用的教程似乎没有使用模块,但您是 - 您的代码有导入和导出。因此,如果不使用额外的业力插件,我无法看到如何回答。
-
@sreekanth 我不确定如何在 Plunker 上运行它,因为我不确定 npm 如何与之交互。我很抱歉。如果有帮助,我创建了一个 github 存储库来演示问题:github.com/jammerware/karma-question。只需克隆、npm install 和 npm test。
-
@cartant 你说得很好。这可能是导致我的问题的误解。我在教程中看到作者正在使用 ///
语句来公开被测对象,但我不确定我是否真的理解它是如何工作的。很抱歉造成混淆 - 我是 JS 测试的新手。请参阅我在之前的评论中链接的 github 存储库。如果你要解决这个问题,你会使用插件吗?你会使用业力浏览器吗?感谢您的帮助和时间。
标签: typescript jasmine karma-runner