javascript - 如何在 Node.js 中测试错误回调

标签 javascript node.js mocha.js chai

我在 Node 项目中使用 Mocha 和 Chai,想知道如何测试 Node 函数中的错误回调?

这是我要测试的代码示例:

  savePlayer: function(player) {

  var playerName =  player.name;

    modules.fs.writeFile('./Data/' + playerName + '.json', JSON.stringify(player), function (err) {
      if (err) {
        return console.log(err.message);
      }
    });
}

这是我的测试:

describe("savePlayer", function() {
  it("Should save the player in JSON, using thier name", function() {

     var player = {name: "test" }

    modules.data.savePlayer(player);

   var playerFile =  modules.fs.readFileSync('Data/test.json').toString('utf8');

    expect(playerFile).should.exist;

  });
});

这通过了,但我想要完整的代码覆盖率。这行 return console.log(err.message); 未经测试,我不确定如何伪造错误并测试控制台是否报告错误。

最佳答案

这是一个使用 sinon 的注释示例和 chai :

var fs         = require('fs');
var sinon      = require('sinon');
var expect     = require('chai').expect;
var savePlayer = require('your-module').savePlayer;

describe('savePlayer', function() {
  // We spy on `console.log()` calls. Spying means that calls to this function
  // are recorded, and we can check to see if it, for instance, was called with
  // particular arguments.
  var consoleSpy = sinon.spy(console, 'log');

  // We stub `fs.writeFile()`. Stubbing means that calls to this function 
  // are taken over, and we can determine exactly how it should act.
  var fsStub     = sinon.stub(fs, 'writeFile');

  // Before each test, the spy and stub are reset.
  beforeEach(function() {
    consoleSpy.reset();
    fsStub.reset();
  });

  // After _all_ tests, the original functions are restored.
  after(function() {
    consoleSpy.restore();
    fsStub.restore();
  });

  // Test #1: if `fs.writeFile()` fails, it should trigger a call to `console.log`.
  it('should log an error when `fs.writeFile` fails', function() {
    var msg = 'my test error';

    // Here we let `fs.writeFile()` call the callback with an error.
    fsStub.yields( new Error(msg) );

    // Call your function.
    savePlayer({ name : 'xx' });

    // Check to make sure that `console.log()` is called with the same error message.
    expect( consoleSpy.calledWith(msg) ).to.be.true;
  });

  // Test #2: when `fs.writeFile()` went okay, nothing should be logged.
  it('should not log an error when `fs.writeFile` is okay', function() {
    // As per Node convention, falsy first argument means 'no error'.
    fsStub.yields( null );

    // Call your function.
    savePlayer({ name : 'xx' });

    // We expect that `console.log()` wasn't called.
    expect( consoleSpy.called ).to.be.false;
  });

});

关于javascript - 如何在 Node.js 中测试错误回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33998896/

相关文章:

javascript - Jquery cookie,适用于背景颜色但不适用于 Logo 图像

javascript - 更改Chrome扩展程序窗口的位置和大小

node.js - 带有 mocha 的 Node 检查器无法使用 'debugger' 命令

javascript - Mocha ES6 巴别塔 "TypeError: undefined is not a function"

node.js - 动态运行 Mocha 测试

javascript - onmouseover 和 jquery 函数无法正常工作

node.js - Angular 8 错误 : '"node --max-old-space-size=1024 0"' is not recognized as an internal or external command

node.js - 如何在不修改源代码的情况下获得 Mocha 测试的代码覆盖率?

node.js - 哪个 nosql 数据库适合?

javascript - polymer 双向数据绑定(bind)不起作用