【发布时间】:2015-09-03 15:25:53
【问题描述】:
我有一个 Ajax 请求的 Mocha (Chai?) 测试,它在使用 HTML 文件作为测试运行程序时有效,但在从 PhantomJS 运行时无效。
Karma 正在成功运行其他测试。
我的问题:
为什么 Karma 会失败?
如何让这个测试在 PhantomJS 中运行?
业力报告:
PhantomJS 1.9.8 (Linux 0.0.0) MyAPI "before each" hook for "should parse fetched data as JSON" FAILED
TypeError: 'undefined' is not a function (evaluating 'function(xhr) {
this.requests.push(xhr);
}.bind(this)')
at [...]ajax_test_demo.test.js:22
测试文件:
chai.should();
describe('MyAPI', function() {
// var bike_app = new BikeApp();
beforeEach(function() {
this.xhr = sinon.useFakeXMLHttpRequest();
this.requests = [];
this.xhr.onCreate = function(xhr) {
this.requests.push(xhr);
}.bind(this);
});
afterEach(function() {
this.xhr.restore();
});
it('should parse fetched data as JSON', function(done) {
var data = { foo: 'bar' };
var dataJson = JSON.stringify(data);
myapi.get(function(err, result) {
result.should.deep.equal(data);
done();
});
this.requests[0].respond(200, { 'Content-Type': 'text/json' }, dataJson);
});
});
想法
Karma 似乎在运行 Sinon,调用 sinon.useFakeXMLHttpRequest 时没有任何抱怨,但该调用返回的对象缺少 onCreate 方法。唉,我的 JavaScript 很弱,我不知道如何调试。
HTML 测试运行器:
<!DOCTYPE html>
<html>
<head>
<title>Mocha Tests</title>
<link rel="stylesheet" href="node_modules/mocha/mocha.css">
</head>
<body>
<div id="mocha"></div>
<script src="node_modules/mocha/mocha.js"></script>
<!-- edit from source file -->
<script src="node_modules/sinon/pkg/sinon.js"></script>
<script src="node_modules/chai/chai.js"></script>
<script>mocha.setup('bdd')</script>
<script src="lib/myapi.js"></script>
<script src="test/ajax_test_demo.test.js"></script>
<script>
mocha.run();
</script>
</body>
</html>
Karma 配置:
'use strict';
var appConfig = require('./config');
module.exports = function(config) {
config.set({
basePath: '',
frameworks: [
'sinon',
'mocha',
'chai',
'fixture',
],
files: [
'lib/*.js',
'test/*.js',
'test/*.html'
],
preprocessors: appConfig.karma.preprocessors,
reporters: appConfig.karma.reporters,
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: appConfig.karma.autoWatch,
browsers: appConfig.karma.browsers,
singleRun: appConfig.karma.singleRun
});
};
杂项
我正在学习本教程:https://www.airpair.com/javascript/posts/unit-testing-ajax-requests-with-mocha
【问题讨论】:
-
无论您是在浏览器中还是在 CLI 中,Karma 都在运行测试; PhantomJS 是后一种情况下的浏览器。此问题在 PhantomJS 中,与 Mocha/Chai/Karma 无关。
标签: javascript phantomjs