Sinon Stub无法正常工作并调用原始功能

时间:2019-07-15 09:53:41

标签: node.js unit-testing mocha sinon chai

我正在为我的一个异步函数编写单元测试,并且正在从中调用另一个异步函数,我想对异步调用进行存根并返回所需的值。

我已经使用sinon.stub对该函数进行了存根,并尝试使用sandbox.create()仍然没有运气。仍然是mu函数正在调用原始函数,并且出现超时错误,我已将超时设置为15000。

这是我调用另一个同步功能的函数

async function performMaccheckPortbounce(requestBody){
  return new Promise(async (resolve, reject) =>{

const trunkCheckResult = await performportTrunkCheck(requestBody);

    var isTrunked = trunkCheckResult.toString().match(/switchport mode trunk/);
    console.log('isTrunked -> '+isTrunked);
    console.log(JSON.stringify(isTrunked));
    if (isTrunked == 'switchport mode trunk') {
     return resolve("ERROR_CODE_INVALID_PORTMODE");
   }
});
}
async function performportTrunkCheck(requestBody){
    return new Promise((async (resolve, reject) => {

      var dataOut = [];

      let config = global.sw_config;
      config.hostname = requestBody.hostname;
      let port_number = requestBody.port_number;

      let command = `sh run interface ${port_number}`;
      var conn = new Client();
      conn.on('ready', function() {
        console.log('Client :: ready');
        conn.shell(function(err, stream) {
          if (err) throw err;
          stream.on('close', function() {
            console.log('Stream :: close trunk');
            console.log(dataOut.toString());
            conn.end();
            return resolve(dataOut.toString());
          }).on('data', function(data) {
            dataOut.push(data.toString().split("\r\n"));
            console.log('STDOUT: ' + data);
          }).stderr.on('data', function(data) {
            console.log('STDERR: ' + data);
          });
          var response = stream.end(command+"\nexit");
          console.log(response);
        });
      }).connect(config)
    }));
  }

这是我的测试代码


describe('Mac Check Portbounce Test',  function(){
    let PortTruncChek,sandbox
    let requestBody = {'hostname': 't9394labswt0001',
                        'port_number':'gi4/0/1',
                        'mac_address' : 'a899.69e3.bec0'
                    }

                    }
    before(function(){
        sandbox = sinon.sandbox.create()

    })

    after(function(){
        sandbox.restore()
    })


    it("Should Return Invalid PORT MODE", async function(done){
        this.timeout(15000)

        requestBody.mac_address = 'a899.69e3.bec0';
        sandbox.stub(macCheck, 'performportTrunkCheck').returns(Promise.resolve('/switchport mode trunk/'));

        let result1 =  await macCheck.performMaccheckPortbounce(requestBody);
        assert.equal(result1,"/switchport mode trunk/");
        done();

    })
}) 

它实际上正在调用函数performportTrunkCheck并抛出以下错误

1)Mac Check Portbounce测试

   Should Return Invalid PORT MODE:
 Error: Timeout of 15000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/Users/z003878/Network_API/NetworkApi/network-switch-configurations-v1-maccheckportbounce/test/maccheckportbounce-test.js)

1 个答案:

答案 0 :(得分:0)

如果你的模块是 CommonJS 模块。然后您可以使用 rewire 包来帮助您模拟/存根 performportTrunkCheck 函数中调用的 performMaccheckPortbounce 函数。

例如

index.js

async function performMaccheckPortbounce(requestBody) {
  return new Promise(async (resolve, reject) => {
    const trunkCheckResult = await performportTrunkCheck(requestBody);

    var isTrunked = trunkCheckResult.toString().match(/switchport mode trunk/);
    console.log('isTrunked -> ' + isTrunked);
    console.log(JSON.stringify(isTrunked));
    if (isTrunked == 'switchport mode trunk') {
      return resolve('ERROR_CODE_INVALID_PORTMODE');
    }
  });
}

async function performportTrunkCheck(requestBody) {
  return new Promise(async (resolve, reject) => {
    var dataOut = [];

    let config = global.sw_config;
    config.hostname = requestBody.hostname;
    let port_number = requestBody.port_number;

    let command = `sh run interface ${port_number}`;
    var conn = new Client();
    conn
      .on('ready', function () {
        console.log('Client :: ready');
        conn.shell(function (err, stream) {
          if (err) throw err;
          stream
            .on('close', function () {
              console.log('Stream :: close trunk');
              console.log(dataOut.toString());
              conn.end();
              return resolve(dataOut.toString());
            })
            .on('data', function (data) {
              dataOut.push(data.toString().split('\r\n'));
              console.log('STDOUT: ' + data);
            })
            .stderr.on('data', function (data) {
              console.log('STDERR: ' + data);
            });
          var response = stream.end(command + '\nexit');
          console.log(response);
        });
      })
      .connect(config);
  });
}

module.exports = { performMaccheckPortbounce, performportTrunkCheck };

index.test.js

const rewire = require('rewire');
const sinon = require('sinon');
const { assert } = require('chai');

describe('Mac Check Portbounce Test', function () {
  let sandbox;
  let requestBody = { hostname: 't9394labswt0001', port_number: 'gi4/0/1', mac_address: 'a899.69e3.bec0' };

  before(function () {
    sandbox = sinon.createSandbox();
  });

  after(function () {
    sandbox.restore();
  });

  it('Should Return Invalid PORT MODE', async function () {
    this.timeout(15000);

    requestBody.mac_address = 'a899.69e3.bec0';
    const performportTrunkCheckStub = sandbox.stub().resolves('/switchport mode trunk/');

    macCheck = rewire('./index');
    macCheck.__set__('performportTrunkCheck', performportTrunkCheckStub);

    let result1 = await macCheck.performMaccheckPortbounce(requestBody);
    sandbox.assert.calledWithExactly(performportTrunkCheckStub, requestBody);
    assert.equal(result1, 'ERROR_CODE_INVALID_PORTMODE');
  });
});

单元测试结果:

  Mac Check Portbounce Test
isTrunked -> switchport mode trunk
["switchport mode trunk"]
    ✓ Should Return Invalid PORT MODE (1279ms)


  1 passing (1s)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |   26.67 |       25 |   22.22 |   27.59 |                   
 index.js |   26.67 |       25 |   22.22 |   27.59 | 15-44             
----------|---------|----------|---------|---------|-------------------