2017-10-08 106 views
-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, 
}; 

有人可以告訴我如何拋出錯誤並測試該錯誤嗎?

+1

什麼是'拋出新的錯誤( '抓我')'的目的是什麼? – guest271314

+0

我想要它拋出一個錯誤,所以我可以測試錯誤處理...否則,現在,它不起任何其他目的... –

+1

該代碼確實處理來自'await Story.createStory(ctx。 request.body)'at'catch(){}'。代碼還會在'catch(){}'處創建一個新的'Error',原因不明。 – guest271314

回答

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

 
});

相關問題