簡體   English   中英

摩卡和詩乃發行JS單元測試

[英]Mocha and Sinon issue with JS Unit test

這是我連接兩個字符串的基本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>摩卡R:\\ abc \\ js-unit-test \\ test.js

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

TypeError: context.getVariable is not a function

您需要在此處導入實際上下文,然后使用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");
  });
}); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM