我的应用程序中有几个基于类的助手,主要是为了包含 i18n 服务。一切都很好,但是,我想不出一种方法来测试它们。
自动生成的测试不工作,因为它期望导出一个函数并提示,undefined 不是构造函数
:
module('Unit | Helper | format number');
// Replace this with your real tests.
test('it works', function(assert) {
let result = formatNumber([42]);
assert.ok(result);
});
所以我尝试使用 moduleFor
因为它已经可以用于测试 mixin,但也失败了:
moduleFor('helper:format-number', 'Unit | Helper | format number', {
needs: ['service:i18n']
});
test('it works', function(assert) {
let result = FormatNumber.compute(42);
assert.ok(result);
});
我尝试了所有不同版本的实例化助手对象并对其调用计算但没有任何效果。最后,它要么总是返回 null
,要么因 undefined
错误而失败。
有人在我失败的地方成功了吗?
最佳答案
您的示例中的问题是您试图将 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');
});
});
这里的关键是在每次测试运行时(在 beforeEach
回调中)我创建一个新的助手实例,然后创建一个函数,我的测试可以调用模板助手的相同方式将被调用 (this.helper
)。这让测试看起来尽可能像真实代码,同时仍然让我能够在测试期间修改帮助程序类,您也可以在 beforeEach
回调中看到这一点。
关于javascript - EmberJS : Unit test class-based helpers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39371657/