JS单元测试的摩卡咖啡和Sinon问题



这是我的基本js串联两个字符串, context.getVariable是我想使用sinon嘲笑的东西,

//util.js
var p;
function concat(p) {
  var first_name = context.getVariable('first_name');
  var res = p.concat(first_name);
  return res;
}
concat(p);

我添加了此test.js

var expect = require('expect.js');
var sinon = require('sinon');
var rewire = require('rewire');
var app = rewire('./util.js');
var fakeContext = {
  getVariable: function(s) {}
}
var contextGetVariableMethod;
beforeEach(function () {
  contextGetVariableMethod = sinon.stub(fakeContext, 'getVariable');
});
afterEach(function() {
  contextGetVariableMethod.restore();
});
describe('feature: concat', function() {
  it('should concat two strings', function() {
    contextGetVariableMethod.withArgs('first_name').returns("SS");
    app.__set__('context', fakeContext);
    var concat = app.__get__('concat');
    expect(concat("988")).to.equal("988SS");
  });
}); 

我正在跑步,

node_modules.bin> mocha r: abc js-nit-test test.js

util.js:7
    var first_name = context.getVariable('first_name');
                             ^
TypeError: context.getVariable is not a function

您需要在此处导入实际上下文,然后使用sinon.stub模拟该getVaria -getVaria -getVaria -getvaria -getvaria -getvaria -getvaria -getable方法,以便在实际代码运行时会得到该方法。

var expect = require('expect.js');
var sinon = require('sinon');
var rewire = require('rewire');
var context = require('context') // give correct path here
var app = rewire('./util.js');
var fakeContext = {
  getVariable: function(s) {}
}
beforeEach(function () {
  contextGetVariableMethod = sinon.stub(context, 'getVariable');
});
afterEach(function() {
  contextGetVariableMethod.restore();
});
describe('feature: concat', function() {
  it('should concat two strings', function() {
    contextGetVariableMethod.withArgs('first_name').returns("SS");
    var concat = app.__get__('concat');
    expect(concat("988")).to.equal("988SS");
  });
}); 

最新更新