未处理的承诺投掷错误时拒绝
问题描述:
我写了一个测试来检查我的函数是否有错误捕获。当功能错误时,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,
};
有人可以告诉我如何抛出错误并测试该错误吗?
答
问题是控制器返回一个承诺。使用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;
});
});
什么是'抛出新的错误( '抓我')'的目的是什么? – guest271314
我想要它抛出一个错误,所以我可以测试错误处理...否则,现在,它不起任何其他目的... –
该代码确实处理来自'await Story.createStory(ctx。 request.body)'at'catch(){}'。代码还会在'catch(){}'处创建一个新的'Error',原因不明。 – guest271314