2016-11-12 44 views
0

我正在測試作爲promise的一部分返回的函數。我正在使用chai-as-promised測試已由promise返回的函數 - 檢查錯誤

我可以測試該功能的工作原理,但我無法測試它正確地引發錯誤。

我想測試一下,留出大量的相關承諾代碼的功能:

// function that we're trying to test 
submitTest = (options) => { 
    // missingParam is defined elsewhere. It works - the error is thrown if screenshot not passed 
    if (missingParam(options.screenShot)) throw new Error('Missing parameter'); 

    return {}; 
} 

我的測試:

describe('SpectreClient()', function() { 
    let client; 

    before(() => client = SpectreClient('foo', 'bar', testEndpoint)); 
    // the client returns a function, submitTest(), as a part of a promise 

    /* 
    omitting tests related to the client 
    */ 

    describe('submitTest()', function() { 
    let screenShot; 
    before(() => { 
     screenShot = fs.createReadStream(path.join(__dirname, '/support/test-card.png')); 
    }); 

    // this test works - it passes as expected 
    it('should return an object',() => { 
     const submitTest = client.then((response) => { 
     return response.submitTest({ screenShot }); 
     }); 
     return submitTest.should.eventually.to.be.a('object'); 
    }); 

    // this test does not work - the error is thrown before the test is evaluated 
    it('it throws an error if not passed a screenshot',() => { 
     const submitTest = client.then((response) => { 
     return response.submitTest({}); 
     }); 

     return submitTest.should.eventually.throw(Error, /Missing parameter/); 
    });  
    }); 
}) 

測試的輸出 -

// console output 
1 failing 

1) SpectreClient() submitTest() it throws an error if not passed a screenshot: 
    Error: Missing parameter 

如何測試錯誤是否被引發correclty?我不確定這是摩卡問題還是承諾的事情還是承諾的事情。非常感謝。

回答

0

承諾處理程序中引發的異常轉換爲承諾拒絕。 submitTest在回調內執行到client.then,因此它引發的異常變爲承諾拒絕。

所以,你應該這樣做:

return submitTest.should.be.rejectedWith(Error, /Missing parameter/)