投掷错误时未处理的承诺拒绝

时间:2017-10-08 14:44:55

标签: javascript tdd sinon koa

我已经编写了一个测试来检查我的错误捕获功能。当函数错误时,将调用next()。我想重写它,所以函数抛出一个错误,我可以使用spy.should.have.thrown(error)。但是,当我尝试抛出错误时,我不断收到警告:

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: catch me

DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code

测试:

const chai = require('chai');
const sinon = require('sinon');
const sinonChai = require('sinon-chai');
chai.should();
chai.use(sinonChai);

const mockStory = {};
const proxyquire = require('proxyquire');

//creates mock model functions to replace original model functions in controller
const Story = proxyquire('../controller/controller',
  { '../model/model' : mockStory}
);

describe('Story should be created', () => {

  const ctx = {request: {body:'foo'}};

  it ('createStory should catch errors from model', async () => {
    const foo = ctx.request.body;
    mockStory.createStory = (foo) => {
      throw new Error('error');
    };
    const next = sinon.spy();
    const res = Story.createStory(ctx, next);
    next.should.have.been.called;
  });

});

正在测试的控制器上的功能:

const mongoose = require('mongoose');
const Story = require('../model/model');
const Console = console;

const createStory = async (ctx, next) => {
  try {
    const createdStory = await Story.createStory(ctx.request.body);
    ctx.status = 200;
  } catch (error) {
    next(error);
    //gives unhandled promise rejection warning...
    throw new Error('catch me')
  }
};

module.exports = {
  createStory,
};

有人可以告诉我如何抛出错误并测试该错误吗?

1 个答案:

答案 0 :(得分:0)

问题是控制器返回一个承诺。使用chai-as-promised库解决了错误。



//controller.js
const createStory = async (ctx, next) => {
  try {
    const createdStory = await Story.createStory(ctx.request.body);
    ctx.status = 200;
  } catch (error) {
    ctx.throw('Could not create story!');
  }
};

//tests.js

const chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
chai.should();

const mockStoryModel = {};
const proxyquire = require('proxyquire');

const StoriesController = proxyquire('../controller/controller',
  { '../model/model' : mockStoryModel}
);

describe('Story', () => {

  const ctx = {request: {body:'foo'}};

  it ('createStory should catch errors from model', async () => {
    const foo = ctx.request.body;
    mockStory.createStory = (foo) => {
      throw new Error('error');
    };
    Story.createStory().should.be.rejected;
  });

});