使用mocha找不到功能的单元测试

时间:2016-03-03 16:37:31

标签: node.js testing mocha

所以我试图单元测试我在这里编写的函数是函数:

function compareServices(service1, service2) {
  if (service1.name != service2.name) {
    return false
  }
  if (service1.port != service2.port) {
    return false
  }
  if (service1.target != service2.target) {
    return false
  }
  if (service1.address != service2.address) {
    return false
  }

  return true
}

它位于我的main.js文件中。现在,当我尝试运行测试时,我收到一条错误消息:

 Main #compareServices() should compare if two services match:
 TypeError: main.compareServices is not a function
  at Context.<anonymous> (test/stelaSpec.js:21:25

这是我的测试文件:

var expect = require("chai").expect;
var main = require("../src/main.js");

describe("Main", function(){
  describe('#compareServices()', function() {
    it('should compare if two services match', function() {
      var svc1 = {
        "name": "test.fg.service",
        "port": 8001,
        "target": "mac-book",
        "address": "192.2.2.2"
      }

      var svc2 = {
        "name": "test.fg.service",
        "port": 8001,
        "target": "mac-book",
        "address": "192.2.2.2"
      }

      var result = main.compareServices(svc1, svc2);

      expect(result).equal(true)
    });
  });
});

为什么它说它不是一个功能呢?

2 个答案:

答案 0 :(得分:1)

确保在main.js文件末尾包含以下内容:

module.exports = {
  compareServices: compareServices
};

这将使其他需要它的javascript文件可以访问该函数。

答案 1 :(得分:0)

您可以更改main.js的代码,如下所示:

function compareServices(service1, service2) {
    if (service1.name != service2.name) {
        return false
    }
    if (service1.port != service2.port) {
        return false
    }
    if (service1.target != service2.target) {
        return false
    }
    if (service1.address != service2.address) {
        return false
    }

    return true
}

// if you use case => In test file you need to declare var main = new Main();
// with Main = require(... + '/main.js');
var Main = function(){};

Main.prototype.compareServices = function(service1, service2) {
    if (service1.name != service2.name) {
        return false
    }
    if (service1.port != service2.port) {
        return false
    }
    if (service1.target != service2.target) {
        return false
    }
    if (service1.address != service2.address) {
        return false
    }

    return true
}
module.exports = Main;

或者

var Main = function(){};

Main.compareServices = function(service1, service2) {
    if (service1.name != service2.name) {
        return false
    }
    if (service1.port != service2.port) {
        return false
    }
    if (service1.target != service2.target) {
        return false
    }
    if (service1.address != service2.address) {
        return false
    }

    return true
}