node js单元测试:mocking需要依赖 [英] node js unit testing: mocking require dependency

查看:114
本文介绍了node js单元测试:mocking需要依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了将以下设置的单元测试编写为jira.js文件(在node.js模块中)的问题:

I am having issues writing unit test for the following setup as a jira.js file (in a node.js module):

var rest = require('restler'); // https://www.npmjs.com/package/restler

module.exports = function (conf) {
    var exported = {};

    exported.getIssue = function (issueId, done) {
        ...

        rest.get(uri).on('complete', function(data, response) {
        ...
    };

    return exported;
};

现在,我想为我的getIssue函数编写单元测试.'restler'是一个REST客户端,通过它我可以通过我的JIRA API调用JIRA来获取JIRA问题代码。

Now, i want to write unit test for my getIssue function. 'restler' is a REST client through which i make REST calls to the JIRA API to get a JIRA issue via my code.

因此,为了能够测试createIssue(..),我希望能够在我的Jasmine单元测试中模拟'rest'var。

So to be able to test createIssue(..), I want to be able to mock the 'rest' var in my Jasmine unit tests.

我如何模仿这种方法?请给我一些指示,以便我可以继续。我尝试过使用重新连接,但我失败了。

How can i mock this method? Please give me some pointers so that i can go ahead. I have tried using rewire but i have failed.

这是我到目前为止无效的(即.getIssue方法未定义):

This is what i have so far which does not work (ie. getIssue method turns out to be undefined):

var rewire       = require("rewire");
var EventEmitter = require('events').EventEmitter;
var emitter      = new EventEmitter();
var cfg          = require("../../../config.js").Configuration;
var jiraModule   = rewire("../lib/jira")(cfg);
var sinon        = require("sinon");
var should       = require("should");

// https://github.com/danwrong/restler
var restMock = {
    init : function () {
        console.log('mock initiated'+JSON.stringify(this));

    },
    postJson : function (url, data, options) {
        console.log('[restler] POST url='+url+', data= '+JSON.stringify(data)+
        'options='+JSON.stringify(options));
        emitter.once('name_of_event',function(data){
            console.log('EVent received!'+data);
        });
        emitter.emit('name_of_event', "test");
        emitter.emit('name_of_event');
        emitter.emit('name_of_event');
    }, 
    get : function (url, options) {
        console.log('[restler] GET url='+url+'options='+JSON.stringify(options));
    },
    del : function (url, options) {
        console.log('[restler] DELETE url='+url+'options='+JSON.stringify(options));
    },
    putJson : function (url, data, options) {
        console.log('[restler] PUT url='+url+', data= '+JSON.stringify(data)+
        'options='+JSON.stringify(options));
    }
};

var cfgMock = {
    "test" : "testing"
};

jiraModule.__set__("rest", restMock);
jiraModule.__set__("cfg", cfgMock);

console.log('mod='+JSON.stringify(jiraModule.__get__("rest")));

describe("A suite", function() {
it("contains spec with an expectation", function() {
    restMock.init();
    restMock.postJson(null, null, null);

console.log(cfg.jira);

    // the following method turns out to be undefined but when i console.log out the jiraModule, i see the entire code outputted from that file
    jiraModule.getIssue("SRMAPP-130", function (err, result) {
        console.log('data= '+JSON.stringify(result));
     });

    expect(true).toBe(true);
});
});

如果有人可以指导我如何嘲笑'休息'需要依赖&单元测试这个方法会非常有帮助。

If someone can guide me on how to mock the 'rest' require dependency & unit test this method that will be very helpful.

另外,我应该如何模拟传递给module.exports的'conf'?

Also, how should i mock the 'conf' being passed to module.exports?

谢谢

推荐答案

您可以使用 proxyquire 嘲弄来存根/模拟依赖项。

You could use proxyquire or mockery to stub/mock the dependencies.

在下面的示例中,我使用了 proxyquire 。希望它有所帮助。

In the below example I have used proxyquire. Hope it helps.

/* ./src/index.js */
var rest = require('restler');

module.exports = function (conf) {
  var exported = {};

  exported.getIssue = function (issueId, done) {
    var uri = '';
    var reqObj = '';
    var service = {
      auth : ''
    };

    rest.postJson(uri, reqObj, service.auth).on('complete', function(data, response) {
      done(data, response);
    });
  };

  return exported;
};







/* ./test/index.js */
var proxyquire  =  require('proxyquire');
var assert      =  require('chai').assert;
var restlerStub = {
  postJson: function() {
    return {
      on: function(event, callback) {
        callback('data', 'response');
      }
    }
  }
}

var index = proxyquire('../src/index', {'restler': restlerStub})();

describe('index', function() {
  it('should return the desired issue', function(done) {
    var issue = index.getIssue('issueId', function(data, response) {
      assert.equal(data, 'data');
      assert.equal(response, 'response');
      done();
    })
  });
});







/* ./package.json */
{
  "scripts": {
    "test": "mocha"
  },
  "dependencies": {
    "restler": "^3.4.0"
  },
  "devDependencies": {
    "chai": "^3.4.1",
    "mocha": "^2.3.4",
    "proxyquire": "^1.7.3"
  }
}

这篇关于node js单元测试:mocking需要依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆