Sinon Stub 不工作并调用原始函数

Sinon Stub not working and calling the original function

提问人:Pradeep S 提问时间:7/15/2019 最后编辑:Pradeep S 更新时间:12/25/2020 访问量:1210

问:

我正在为我的一个异步函数编写单元测试,它正在从中调用另一个异步函数,我想存根该异步调用并返回我想要的值。

我已经使用并尝试了该功能,但仍然没有运气。仍然mu函数调用原始函数,我收到超时错误,我已将超时设置为15000。sinon.stubsandbox.create()

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

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检查端口弹跳测试

   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)
单元测试 Mocha.js Sinon Chai

评论

0赞 Prakash Thete 7/15/2019
在您的函数中,如果您的条件不为真,应该返回什么?performMaccheckPortbounceif (isTrunked == 'switchport mode trunk')
0赞 Andrew Nolan 7/15/2019
可能将: ' sandbox.stub(macCheck, 'performportTrunkCheck').returns(Promise.resolve('/switchport mode trunk/'));' 更改为:.resolves('/switchport mode trunk/')
0赞 Pradeep S 7/16/2019
@AndrewNolan尝试了相同的错误。sandbox.stub(macCheck, 'performportTrunkCheck')..resolves('/switchport mode trunk/')

答:

0赞 Lin Du 12/25/2020 #1

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

例如

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             
----------|---------|----------|---------|---------|-------------------