Webpack + Karma + Mocha:如何在Mocha测试中使用真正的XmlHttpRequest?

时间:2017-03-20 16:46:38

标签: typescript mocha karma-runner jsdom karma-mocha

问题

我正在尝试测试使用XMLHttpRequest的TypeScript代码。从IDE运行整个Karma测试套件时,测试传递,因为它会打开浏览器并获取提供的XmlHttpRequest和DOM库。作为参考,这是Karma运行命令:

/usr/local/bin/node /Applications/WebStorm.app/Contents/plugins/js-karma/js_reporter/karma-intellij/lib/intellijServer.js --karmaPackageDir=/Users/user/project/node_modules/karma --configFile=/Users/user/project/karma.conf.js

...但是,当单独运行测试 时(通过右键单击测试并在WebStorm IDE中选择“运行”),失败消息ReferenceError: XMLHttpRequest is not defined,因为Mocha未设置为打开浏览器(因此未提供XmlHttpRequest或DOM库)。作为参考,这个Mocha命令是:

/usr/local/bin/node /Users/user/project/node_modules/mocha/bin/_mocha --require ts-node/register --ui bdd --reporter /Applications/WebStorm.app/Contents/plugins/NodeJS/js/mocha-intellij/lib/mochaIntellijReporter.js /Users/user/project/tests/test.ts --grep "XHR "

我可以提供xmlhttprequest库,但是Mocha然后抱怨ReferenceError: document is not defined因为它缺少一个DOM库 - 在这里,我想我需要提供类似jsdom和/或{{ 1}}或让Mocha在浏览器中运行其测试(无论是Firefox还是无头浏览器,如PhantomJS)。然而,经过几个小时的尝试,我得出结论,我无法弄清楚如何。

鉴于我目前的项目设置,我如何使用真正的XHR运行我的个人Mocha测试?

项目文件

最有可能只有mocha-jsdom需要更改,但为了完整性,我已将它们全部包含在内。

karma.conf.js

test.ts

import { expect } from 'chai'; // import {jsdom} from 'jsdom'; // mocha-jsdom? describe("XHR", () => { it("Test should not fail upon XHR.", function(){ new XMLHttpRequest(); }); });

karma.conf.js

var path = require("path"); var webpackConfig = require("./webpack.config"); module.exports = function(config) { config.set({ autoWatch: true, basePath: "", client: { mocha: { reporter: 'html' // require: [require.resolve('jsdom_setup.js')] } }, browsers: ["Firefox"], colors: true, exclude: [], files: [ "tests/test.ts" ], frameworks: ["mocha", "chai"], logLevel: config.LOG_INFO, plugins: [ "karma-*" // "jsdom" // "mocha-jsdom" ], port: 9876, preprocessors: { "*.ts": ["webpack"] }, reporters: ["mocha"], singleRun: false, webpack: { module: webpackConfig.module, resolve: webpackConfig.resolve } }); };

package.json

{ "name": "despair", "version": "1.0.0", "description": "", "main": "webpack.config.js", "scripts": { "start": "webpack --config webpack.config.js --display-error-details", "test": "karma start karma.conf.js" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@types/chai": "^3.4.35", "@types/mocha": "^2.2.40", "chai": "^3.5.0", "jsdom": "^9.12.0", "karma": "^1.5.0", "karma-chai": "^0.1.0", "karma-firefox-launcher": "^1.0.0", "karma-mocha": "^1.3.0", "karma-mocha-reporter": "^2.2.2", "karma-webpack": "^2.0.2", "mocha": "^3.2.0", "ts-loader": "^2.0.1", "ts-node": "^2.1.0", "typescript": "^2.1.5", "watch": "^1.0.1", "webpack": "^2.2.0-rc.7" }, "dependencies": {} }

tsconfig.json

{ "compilerOptions": { "watch": true, "sourceMap": true, "target": "es3", "baseUrl": ".", "outDir": "./build", "allowJs": true, "types": ["mocha", "chai"] // Note: implicit in TypeScript 2 } }

webpack.config.js

0 个答案:

没有答案