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

时间:2015-11-30 12:39:03

标签: javascript node.js mocha chai

我正在使用Mocha和Chai进行节点项目,并想知道如何在节点函数中测试错误回调?

以下是我要测试的代码示例:

  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);未经测试,我不确定如何伪造错误并测试控制台报告错误。

2 个答案:

答案 0 :(得分:5)

以下是使用sinonchai的注释示例:

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;
  });

});

答案 1 :(得分:0)

如果您正在进行单元测试,则需要确保所有内容都是隔离的。这意味着没有第三方或后端连接。

所以你需要存根所有这些。

您的主模块文件看起来像==>

 savePlayer: function(player) {

  var playerName =  player.name;

    modules.fs.writeFile('./Data/' + playerName + '.json', JSON.stringify(player), function (err) {
      if (err) {
        // throw error message
        throw new Error(err.message);
      }
    });
}

示例代码==>

const fs = require('fs)
const sinon = require('sinon')

describe("savePlayer", () => {
  it("Should save file successfully", done => {

     // stub all external connections (your external file)
     const fsStub = fs.stub(fs, 'writeFile')

     // expect save success
     fsStub.yields(null)

     // declare param
     const player = {name: "test" } 

     // execute function
     modules.data.savePlayer(player)

     // test
     expect(fsStub.called).to.be.true

     // clean
     fsStub.restore();
     done();
  });

  it("Should get error", done => {

     // stub all external connections (your external file)
     const fsStub = fs.stub(fs, 'writeFile')

     // expect error
     fsStub.yields(new Error('SOME ERROR OCCURS'))

     // declare param
     const player = {name: "test" } 

     // execute function
     try {
         modules.data.savePlayer(player)
     } catch(e) {
         // test
         expect(e.message).eql('SOME ERROR OCCURS');

         // clean
         fsStub.restore();
         done();
     }
  });
});