【发布时间】:2016-11-11 22:00:26
【问题描述】:
我最近开始学习在 JavaScript 中使用 Jasmine 进行单元测试。现在我正在使用 Karma 测试运行器在 WebStorm 中工作。当我通过控制台对 Jasmine 和 WebStorm 中的 Karma/Jasmine 进行测试时,一些结果有所不同。
例如,当我创建具有以下简化结构的项目时:
.
├── _js
| └── script.js
├── _test
| └── test.js
├── karma.conf.js
└── index.html
script.js
function Card(figure, color) {
"use strict";
var that = this;
this.figure = figure;
this.color = color;
this.toString = function () {
return that.col + that.fig;
};
}
test.js
describe("The validation of name", function () {
it("should return true if object is properly initialized", function () {
var a = new Card(1,"A");
expect(a.figure === 1)
});
it("should return true if array contain card", function () {
var a = [new Card(1,"A"),new Card(1,"B"),new Card(1,"C"),new Card(1,"D")];
console.log(a);
expect(a).toContain({figure: 1, color: "A"});
});
})
karma.conf.js
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: ['js/*.js', 'test/*.js'],
exclude: [],
preprocessors: {},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Firefox'],
singleRun: false,
concurrency: Infinity
})
}
当我在 Jasmine(JSFiddle 上的HERE)上运行这些测试时,它通过了,但在 WebStorm 中它失败了,并且:
[卡片{图:1,颜色:'A',toString:函数(){...}}, Card{figure: 1, color: 'B', toString: function () { ... }}, Card{figure: 1, color: 'C', toString: function () { ... }}, Card{figure: 1, color: 'D', toString: function () { ... }}]
预期 [ NaN, NaN, NaN, NaN ] 包含 Object({ figure: 1, color: '一种' })。 @test/test.js:10:9 [3]http://localhost:9877/context.js:151:7
它从 console.log 打印正确的值,但测试失败,如上所示,对象被视为 NaN。
更重要的是,如果我创建相同的对象,没有new 关键字,通过文字对象表示法,所有测试都没有问题通过。所以这里的构造函数似乎是个问题。
造成这种情况的原因是什么?
【问题讨论】:
标签: javascript jasmine karma-runner webstorm