簡體   English   中英

如何在Mocha中編寫測試用例

[英]How to write test case in mocha

我有這個代碼,我正在嘗試使用mocha(這是我的新手)進行測試。

function ColorMark(){
    this.color = ""
    var that = this;

    this.create = function(color){
        that.color = color;
        console.log("Created a mark with " + that.color + " color");
    }
}

我所做的是這個

describe('ColorMark', function(){
    describe('#create("red")', function(){
        it('should create red mark',function(){
            assert.equal(this.test.parent.ctx.color, "red");
        })
    })
});

錯誤:

AssertionError: "undefined" == "red"

that.color返回undefined

在測試上下文中this什么問題?

我缺少與摩卡咖啡特別相關的東西嗎?

從顯示的代碼來看,它沒有實例化ColorMark也不實際調用create('red') ,您似乎認為Mocha所做的比實際更多。 您在describe的第一個參數中輸入的內容主要是為了您的利益。 這些是測試套件標題。 摩卡咖啡將它們傳遞給記者,然后記者進行展示,僅此而已。

您可以按照以下方法進行操作:

var assert = require("assert");

function ColorMark(){
    this.color = "";
    var that = this;

    this.create = function(color){
        that.color = color;
        console.log("Created a mark with " + that.color + " color");
    };
}

describe('ColorMark', function(){
    describe('#create("red")', function(){
        it('should create red mark',function(){
            var cm = new ColorMark();
            cm.create("red");
            assert.equal(cm.color, "red");
        });
    });
});

您需要設置一個beforeEach()子句來設置測試並執行ColorMark()函數。

從文檔中: http : //mochajs.org/

  beforeEach(function(done){
    db.clear(function(err){
      if (err) return done(err);
      db.save([tobi, loki, jane], done);
    });
  })

所以在這種情況下,它看起來像

function ColorMark(color){
    this.color = ""
    var that = this;

    this.create = function(color){
        that.color = color;
        console.log("Created a mark with " + that.color + " color");
    }
}

beforeEach(function(){
    ColorMark("red");
});

describe('#create("red")', function(){
    it('should create red mark',function(){
        assert.equal(this.test.parent.ctx.color, "red");
    })
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM