-1
我寫了一個測試來檢查我的函數是否有錯誤捕獲。當功能錯誤時,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,
};
有人可以告訴我如何拋出錯誤並測試該錯誤嗎?
什麼是'拋出新的錯誤( '抓我')'的目的是什麼? – guest271314
我想要它拋出一個錯誤,所以我可以測試錯誤處理...否則,現在,它不起任何其他目的... –
該代碼確實處理來自'await Story.createStory(ctx。 request.body)'at'catch(){}'。代碼還會在'catch(){}'處創建一個新的'Error',原因不明。 – guest271314