【问题标题】:Jasmine and Karma with Jasmine gives different resultsJasmine 和 Karma 与 Jasmine 给出不同的结果
【发布时间】: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


    【解决方案1】:

    你的测试不会通过。

    因为toContain 检查所有对象以包含已定义的属性。

    所以你必须编写你的自定义匹配器。

    检查这个例子:

    // source code
    function Card(figure, color) {
      "use strict";
    
      var that = this;
      this.figure = figure;
      this.color = color;
      this.toString = function () {
        return that.color + that.figure;
      };
    }
    
    var customMatchers = {
      hasObjectInArrayThatContains : function(expected){
        var arrayOfObjects = this.actual;
        // iterating array of objects and finding at least
        // one cituation where it passes test
        for(var i in arrayOfObjects) {
          var failures = 0;
          for(var key in expected) {
            if(arrayOfObjects[i][key] != expected[key]) {
              failures++;
            }
          }
          
          if(failures == 0) {
            return true;
          }
        }
        
        return false;
      } 
    };
    
    describe("The validation of name", function () {
      
      beforeEach(function(){
        this.addMatchers(customMatchers); // attaching our custom matchers
      });
      
      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")];
        expect(a).hasObjectInArrayThatContains({figure: 1, color: "A"}); // using our custom method
      });
    });
    
    
    // load jasmine htmlReporter
    (function() {
      var env = jasmine.getEnv();
      env.addReporter(new jasmine.HtmlReporter());
      env.execute();
    }());
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.css">
    <script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.js"></script>
    <script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine-html.js"></script>

    和失败的例子:

    见:expect(a).hasObjectInArrayThatContains({figure: 1, color: "E"})

    // source code
    function Card(figure, color) {
      "use strict";
    
      var that = this;
      this.figure = figure;
      this.color = color;
      this.toString = function () {
        return that.color + that.figure;
      };
    }
    
    var customMatchers = {
      hasObjectInArrayThatContains : function(expected){
        var arrayOfObjects = this.actual;
        // iterating array of objects and finding at least
        // one cituation where it passes test
        for(var i in arrayOfObjects) {
          var failures = 0;
          for(var key in expected) {
            if(arrayOfObjects[i][key] != expected[key]) {
              failures++;
            }
          }
          
          if(failures == 0) {
            return true;
          }
        }
        
        return false;
      } 
    };
    
    describe("The validation of name", function () {
      
      beforeEach(function(){
        this.addMatchers(customMatchers); // attaching our custom matchers
      });
      
      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")];
        expect(a).hasObjectInArrayThatContains({figure: 1, color: "E"}); // using our custom method
      });
    });
    
    
    // load jasmine htmlReporter
    (function() {
      var env = jasmine.getEnv();
      env.addReporter(new jasmine.HtmlReporter());
      env.execute();
    }());
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.css">
    <script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.js"></script>
    <script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine-html.js"></script>

    工作小提琴:https://jsfiddle.net/3VuGs/396/

    另请阅读:testing Your js with Jasmine

    【讨论】:

    • 但是,当我使用 jasmine-node 通过控制台运行它时,为什么要通过测试?并在链接的 jsfiddle 中?
    • 在 jsfiddle 你使用的是 jasmine v.1.3.1,所以原因可能是 jasmine 的版本和包含函数的差异。
    猜你喜欢
    • 2012-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    • 2014-01-10
    • 2016-03-19
    • 1970-01-01
    相关资源
    最近更新 更多