Test for throwing Errors in Ember.js
Asked Answered
S

2

5

Using the integrated QUnit testing framweork I need to test wether or not visiting a route causes an Error to be thrown.

There is a Handlebars helper in the route that should throw an Error under certain conditions (failed Assertion). How do I test wether or not this Error is thrown?

This is what I got so far:

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

But it does not work, as the Error is not caught by throws(...) and bubbles up to the testing framework, marking this test as failed.

This is the test output:

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)

As visit('/missing') returns a promise, one would assume that using .then(success, error) would work, but it does not.

Stock answered 21/1, 2015 at 5:23 Comment(0)
E
10

I came to this question looking for how to test for an expected error when a component renders. To test for an expected error of say

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

from your component. Then your test can be something like:

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');
});
Equiponderance answered 16/12, 2015 at 10:58 Comment(1)
As of Ember 2.11, assert throws seems to no longer be a thing. github.com/emberjs/ember.js/pull/14898Habitable
O
1

As described on http://api.qunitjs.com/throws/ you're supposed to pass a callback to throws instead of calling the function.

So:

test('throws, if the SVG is missing', function() {
  throws(function() {visit('/missing')}, Error, "has thrown an Error");
});
Offshoot answered 21/1, 2015 at 12:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.