简体   繁体   中英

Mocha and Sinon issue with JS Unit test

This is my basic JS to concatenate two strings, the context.getVariable is something which I want to mock using 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);

I have added this 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");
  });
}); 

I am running,

node_modules.bin> mocha R:\\abc\\js-unit-test\\test.js

util.js:7
    var first_name = context.getVariable('first_name');
                             ^

TypeError: context.getVariable is not a function

You need to import actual context here and then use sinon.stub to mock that getVariable method so it it will get that method when your actual code is running.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM