如何在Node中运行用TypeScript编写的Jasmine测试

4

我希望测试我的用TypeScript编写的Express应用程序。 基本上,我使用Jasmine(编写测试用例),Webpack(将TS打包为JS)和Karma(测试运行器)。

请查找这些文件。

// about.service.ts - code to be tested
import { MongoClient, MongoError, Collection, ObjectId } from 'mongodb';

export class AboutService { // functionality }

// about.service.spec.ts - test cases
import { AboutService} from 'about.service.ts';

describe('services.about.service.spec', () => {
   it('should_return_null_date', () => {
       // test cases here
   });
});

// karma.conf.js - karma configuration file
var webpackConfig = require('./karma.webpack');

module.exports = function (config) {
config.set({
    frameworks: ['jasmine'],
    plugins: [
        require('karma-jasmine'),
        require('karma-chrome-launcher'),
        require('karma-jasmine-html-reporter'),
        require('karma-webpack')
    ],
    files: [
        'somefiles'
    ],
    mime: {
        'text/x-typescript': ['ts']
    },
    preprocessors: {
        'somefiles': ['webpack']
    },
    webpack: webpackConfig,
    reporters: ['kjhtml'],
    browsers: ['Chrome'],
    client: {
        clearContext: false,
        captureConsole: false
    },
    port: 9876,
    colors: true,
    logLevel: config.LOG_WARN,
    autoWatch: true,
    singleRun: false,
    concurrency: Infinity
 });
}

// karma.webpack.js
var nodeExternals = require('webpack-node-externals');
module.exports = {
    resolve: { extensions: ['.ts', '.js'], },
    module: {
      rules: [{
        test: /\.ts$/,
        use: ['awesome-typescript-loader']
      }]
    },
    target: "node",
    externals: [nodeExternals()]
 }

Webpack编译成功了,但当Karma在Chrome中启动时,它却显示“require('mongodb')未找到”,我猜测在浏览器中不支持require。
我想知道如何在Node环境中运行测试,而不是在浏览器中?是否有任何karma加载程序可用?我想要在jasmine中编写测试,并且我需要Webpack将ts转换为js。我想要一个类似于karma的测试运行程序,可以在Node中运行而不是在浏览器中?
非常感谢您的帮助。
1个回答

4

该项目目前不仅使用了Jasmine,还使用了Karma。 Karma runner 用于在浏览器中运行测试,不适合仅在Node.js中运行。

测试需要直接使用Jasmine runner 运行。对于Node项目而言,通常不需要Webpack,应使用target: 'es6'module: 'commonjs'选项编译TypeScript文件。

有一些选项可以避免使用TypeScript编译步骤,如第三方包jasmine-ts

另一个选择是切换到支持预处理器和因此在Node.js测试中具有改进的TypeScript支持的测试框架和运行程序 - Jest就是其中之一。


谢谢,那我是不是应该直接使用Jasmine运行器,但我认为我需要从ts到js进行编译阶段,对吗? - user3205479
是的。或者使用jasmine-ts跳过编译,它使用ts-node来运行Jasmine。在2018年,我个人会选择Jest。它的模块模拟功能在Node中是不可或缺的。 - Estus Flask
太好了,它可以工作。我认为moq.ts是一个很棒的用于模拟TypeScript的框架。你觉得呢? - user3205479
我不确定它在实际场景中的表现如何。它看起来有点奇怪,因为存根、模拟和间谍是不可分割的,而且它没有涵盖间谍。此外,它也没有得到测试框架的支持,因此无法与其断言集成 - 这是较小库的问题。但还是谢谢,我会仔细研究它的。 - Estus Flask

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接