繁体   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