2015-01-21 29 views
5

使用集成的QUnit測試framweork我需要測試是否訪問路由會導致拋出錯誤。在Ember.js中引發錯誤的測試

路線中有一個把手助手,在某些情況下應該拋出一個錯誤(失敗斷言)。我該如何測試這個錯誤是否被拋出?

這是我走到這一步:

test('throws, if the SVG is missing', function() { 
    throws(visit('/missing'), Error, "has thrown an Error"); 
}); 

但它不工作,因爲錯誤沒有被抓到throws(...)和泡沫到測試框架,這標誌着本次測試爲失敗。

這是測試輸出:

Died on test #1  at http://localhost:7357/assets/dummy.js:304:5 
    at requireModule (http://localhost:7357/assets/vendor.js:77:29) 
    at http://localhost:7357/assets/test-loader.js:14:29: Assertion Failed: No SVG found for this/svg/is/missing 
Source:  
Error: Assertion Failed: No SVG found for this/svg/is/missing 
    at new Error (native) 
    at Error.EmberError (http://localhost:7357/assets/vendor.js:27463:23) 
    at Object.Ember.assert (http://localhost:7357/assets/vendor.js:17077:15) 
    at inlineSvg (http://localhost:7357/assets/dummy.js:94:13) 
    at Object.bindView.normalizedValue (http://localhost:7357/assets/vendor.js:20498:21) 
    at Object.SimpleHandlebarsView.render (http://localhost:7357/assets/vendor.js:23450:26) 
    at EmberRenderer_createElement [as createElement] (http://localhost:7357/assets/vendor.js:52738:16) 
    at EmberRenderer.Renderer_renderTree [as renderTree] (http://localhost:7357/assets/vendor.js:23840:24) 
    at EmberRenderer.<anonymous> (http://localhost:7357/assets/vendor.js:23917:16) 
    at DeferredActionQueues.invoke (http://localhost:7357/assets/vendor.js:13891:18) 

由於visit('/missing')回報的承諾,人們會認爲使用.then(success, error)會的工作,但事實並非如此。

回答

10

我來到了這個問題,在尋找如何測試一個預期的錯誤,當一個組件呈現。測試預期的錯誤說

throw new Error('I am an error'); 

從您的組件。然後你的測試可以是這樣的:

test('my-component should throw an error', function(assert) { 
    assert.expect(1); 

    assert.throws(() => { 
    this.render(hbs`{{my-component myVariable="XYZ"}}`); 
    }, new Error('I am an error'), 'Expect an error with this message'); 
}); 
+0

截至Ember 2.11,斷言拋出似乎不再是一件事情。 https://github.com/emberjs/ember.js/pull/14898 – snewcomer 2017-04-09 01:44:05

1

http://api.qunitjs.com/throws/所述,您應該將回調傳遞給throws而不是調用該函數。

所以:

test('throws, if the SVG is missing', function() { 
    throws(function() {visit('/missing')}, Error, "has thrown an Error"); 
});