【问题标题】:Test for throwing Errors in Ember.js在 Ember.js 中测试抛出错误
【发布时间】:2015-01-21 05:23:54
【问题描述】:

使用集成的 QUnit 测试框架,我需要测试是否访问路由会导致抛出错误。

路由中有一个 Handlebars 助手,在某些情况下应该抛出错误(断言失败)。如何测试是否抛出此错误?

这是我目前得到的:

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) 会起作用,但事实并非如此。

【问题讨论】:

    标签: ember.js qunit ember-qunit


    【解决方案1】:

    我来这个问题是为了寻找如何在组件呈现时测试预期的错误。测试 say 的预期错误

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

    【讨论】:

    【解决方案2】:

    http://api.qunitjs.com/throws/ 所述,您应该将回调传递给throws,而不是调用该函数。

    所以:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-09
      • 1970-01-01
      • 2021-04-03
      • 2020-10-22
      • 1970-01-01
      • 2012-11-21
      • 2020-12-07
      相关资源
      最近更新 更多