简体   繁体   English

用 sinon 存根嵌套方法调用

[英]Stubbing Nested Method call with sinon

I am trying to stub a nested method call.我正在尝试存根嵌套方法调用。 Give the following module:给出以下模块:

module.exports = {
  setupNewUser: (info, callback) => {
    let user = {
      name: info.name,
      nameLowercase: info.name.toLowerCase()
    };

    try {
      Database.save(user, callback);
    } catch (err) {
      callback(err);
    }
  }
};

How would I stub the Database.save method.我将如何存根Database.save方法。 I did the following:我做了以下事情:

it('should call save once', function() {
  let Database = {
    save: () => {}
  };

  let saveStub = sinon.stub(Database, 'save');

  user.setupNewUser({ name: 'test' }, function() {});

  expect(saveStub.calledOnce).to.be.true;
});

running the test I got运行我得到的测试

AssertionError: expected false to be true断言错误:预期假为真

Here is the unit test solution:这是单元测试解决方案:

user.js : user.js

const Database = require('./db');

module.exports = {
  setupNewUser: (info, callback) => {
    let user = {
      name: info.name,
      nameLowercase: info.name.toLowerCase()
    };

    try {
      Database.save(user, callback);
    } catch (err) {
      callback(err);
    }
  }
};

db.js : db.js

module.exports = {
  save(data, callback) {
    console.log('real save');
  }
};

user.spec.js : user.spec.js

const sinon = require('sinon');
const { expect } = require('chai');
const user = require('./user');
const Database = require('./db');

describe('user', () => {
  it('should call save once', function() {
    let saveStub = sinon.stub(Database, 'save');
    user.setupNewUser({ name: 'test' }, function() {});
    expect(saveStub.calledOnce).to.be.true;
  });
});

Unit test result with coverage report:带有覆盖率报告的单元测试结果:

  user
    ✓ should call save once


  1 passing (7ms)

--------------|----------|----------|----------|----------|-------------------|
File          |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
--------------|----------|----------|----------|----------|-------------------|
All files     |    88.24 |      100 |       60 |    88.24 |                   |
 db.js        |       50 |      100 |        0 |       50 |                 3 |
 user.js      |    83.33 |      100 |      100 |    83.33 |                13 |
 user.spec.js |      100 |      100 |    66.67 |      100 |                   |
--------------|----------|----------|----------|----------|-------------------|

Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/56836235源代码: https : //github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/56836235

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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