2016-09-07 6 views
2

私はアプリにいくつかのクラスベースヘルパーを持っています。そのため、私はi18nサービスを含めることができます。すべてがうまく動作しますが、私はそれらをテストする方法を理解できません。 EmberJS:ユニットテストクラスベースのヘルパー

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

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

は、だから私はそれがすでにミックスインをテストするために働いていたとして moduleForを使用してみましたが、また失敗しました:

自動テストは、それが機能をエクスポートすることを期待して文句としてundefined is not a constructorことを、機能していない生成しました:

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エラーで失敗しました。

誰かが失敗した場所で成功することはできましたか?

答えて

2

あなたの例の問題は、実際に必要なものがクラスのインスタンスであるときに、computeをクラス自体の静的メソッドとして呼び出そうとしていることです。

私がテストしているクラスベースのヘルパーの例です。注意; qunitではなくmochaを使用しますが、すべての概念は同じです。

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コールバックにも表示されています。

+0

'ember-cli-mocha @ 0.12'からは、以下のように統合テストやユニットテストができます:https://github.com/emberjs/ember.js/blob/master/blueprints/helper-test/mocha -0.12-files/tests/__ testType __/helpers/__ name __- test.js – acorncom