微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – node js单元测试:mocking需要依赖

我在将以下设置的单元测试编写为jira.js文件(在node.js模块中)时遇到问题:
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进行REST调用获取JIRA问题.

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

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

这是我到目前为止无法正常工作(即getIssue方法未定义):

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,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);
});
});

如果有人可以指导我如何模仿’休息’需要依赖&单元测试这个方法会非常有帮助.

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

谢谢

解决方法

您可以使用 proxyquiremockery来存根/模拟依赖项.

在下面的例子中我使用了proxyquire.希望它有所帮助.

/* ./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',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',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"
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


什么是深拷贝与浅拷贝?深拷贝与浅拷贝是js中处理对象或数据复制操作的两种方式。‌在聊深浅拷贝之前咱得了解一下js中的两种数据类型:
前言 今天复习了一些前端算法题,写到一两道比较有意思的题:重建二叉树、反向输出链表每个节点 题目 重建二叉树: 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列 {1,2,4,7,3,5,6,8} 和中序遍历序列 {
最近在看回JavaScript的面试题,this 指向问题是入坑前端必须了解的知识点,现在迎来了ES6+的时代,因为箭头函数的出现,所以感觉有必要对 this 问题梳理一下,所以刚好总结一下JavaScript中this指向的问题。
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小
JS怎么获取当前时间戳
JS如何判断对象是否为数组
JS怎么获取图片当前宽高