我有兴趣测试用 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 环境而不是浏览器中运行我的测试?有业力装载机吗?我想在 jasmine 本身编写测试,我需要 webpack 将 ts 转换为 js。我想要的只是一个像 karma 这样的测试运行器,它在 Node 而不是浏览器中运行?
非常感谢任何帮助。
最佳答案
该项目目前不仅使用 Jasmine,还使用 Karma。 Karma runner 应该在浏览器中运行测试,它不适合纯粹在 Node.js 中运行。
需要使用 Jasmine runner 运行测试直接地。 Node 项目通常不需要 Webpack,TypeScript 文件应该使用 target: 'es6'
和 module: 'commonjs'
选项编译。
有一些选项可以避免第三方包的 TypeScript 编译步骤,例如 jasmine-ts
.
另一个选择是切换到测试框架和运行器,它们改进了对预处理器的支持,因此,Node.js 测试中的 TypeScript - Jest 就是。
关于javascript - 如何为 Node 运行用 typescript 编写的 Jasmine 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50201143/