EmberJS:基于类的单元测试助手

irr*_*ncu 6 javascript testing qunit ember.js ember-qunit

我的应用程序中有几个基于类的帮助程序,主要是为了我可以包含 i18n 服务。一切都很好,但是,我无法找到测试它们的方法。

自动生成的测试不起作用,因为它期望导出一个函数并抱怨undefined is not a constructor

module('Unit | Helper | format number');

// Replace this with your real tests.
test('it works', function(assert) {
  let result = formatNumber([42]);
  assert.ok(result);
});
Run Code Online (Sandbox Code Playgroud)

所以我尝试使用它,moduleFor因为它已经可以用于测试混合,但也失败了:

moduleFor('helper:format-number', 'Unit | Helper | format number', {
  needs: ['service:i18n']
});

test('it works', function(assert) {
  let result = FormatNumber.compute(42);
  assert.ok(result);
});
Run Code Online (Sandbox Code Playgroud)

我尝试了实例化辅助对象并在其上调用计算的所有不同版本,但没有任何效果。最后它要么总是返回null,要么因错误而失败undefined

在我失败的地方有人成功了吗?

Ale*_*cia 4

您的示例中的问题是,当您真正需要的是类的实例时,您试图compute作为类本身的静态方法进行调用。

这是我正在测试的基于类的帮助器的示例。笔记; 它使用mocha,而不是qunit,但所有概念都是相同的。

import { expect } from 'chai';
import { beforeEach, describe, it } from 'mocha';
import ShareImage from 'my-app/helpers/share-image';

describe('ShareImageHelper', function() {
  beforeEach(function() {
    this.helperClass = ShareImage.create({
      location: {
        hostWithProtocolAndPort: ''
      }
    });
    this.helper = this.helperClass.compute.bind(this.helperClass);
  });

  it('calculates the `assetPath` correctly', function() {
    const assetPath = this.helperClass.get('assetPath');

    expect(assetPath).to.equal('/assets/images/social/');
  });

  it('calculates the path to an image correctly', function() {
    const value = this.helper(['foo', 'bar', 'baz']);

    expect(value).to.equal('/assets/images/social/foo/bar/baz.png');
  });
});
Run Code Online (Sandbox Code Playgroud)

这里的关键是,在每次测试运行时(在回调中beforeEach),我都会创建一个新的帮助程序实例,然后创建一个函数,我的测试可以调用该函数,就像调用模板帮助程序一样(this.helper)。这使得测试看起来尽可能像真实的代码,同时仍然使我能够在测试期间修改帮助器类,您也可以在回调中看到这一点beforeEach