Мокка и Синон проблема с модульным тестом JS - PullRequest
0 голосов
/ 01 июля 2019

Это мой базовый 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-unit-test \ test.js

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

TypeError: context.getVariable is not a function

1 Ответ

0 голосов
/ 02 июля 2019

Вам необходимо импортировать фактический контекст здесь, а затем использовать sinon.stub, чтобы смоделировать этот метод getVariable, чтобы он получал этот метод, когда ваш реальный код работает.

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");
  });
}); 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...