0

如何在单元测试中访问速记助手以对其进行测试?

例子:

/helpers/full-address.js

import Ember from 'ember';

export default Ember.Helper.helper(function(params, hash) {
  var fullAddress = hash.line1 === "" ? "" : hash.line1 + ", ";
  fullAddress += hash.town === "" ? "" : hash.town + ", " ;
  fullAddress += hash.postCode === "" ? "" : hash.postCode + ", ";

  if (fullAddress.length > 2) {
    fullAddress = fullAddress.replace(/,(\s+)?$/, "");
  }

  return fullAddress;
});

在addresses.hbs中使用速记助手

<h4>Addresses</h4>
{{#each model.addresses key="id" as |address|}}
  <p>
    {{full-address line1=address.line1 town=address.town postCode=address.postCode}}
  </p>
{{/each}}

全地址测试

import { fullAddress } from '../../../helpers/full-address';
import { module, test } from 'qunit';

module('Unit | Helper | full address');

// Replace this with your real tests.
test('it works', function(assert) {
  var line1 = "123 Test Street";
  var town = "My Town";
  var postCode = "TE5 5ST";

  var expected = line1 + ", " + town + ", " + postCode;

  var result = ??? // Call helper here
  assert.equal(result, expected);
});

我如何用这 3 个散列变量调用速记助手?

4

1 回答 1

1

您需要稍微修改您的帮助文件:

import Ember from 'ember';

export function fullAddress(params, hash) {
  let retValue = hash.line1 === "" ? "" : hash.line1 + ", ";
  retValue += hash.town === "" ? "" : hash.town + ", " ;
  retValue += hash.postCode === "" ? "" : hash.postCode + ", ";

  if (retValue.length > 2) {
    retValue = retValue.replace(/,(\s+)?$/, "");
  }

  return retValue;
}

export default Ember.Helper.helper(fullAddress);

然后,您可以编写测试:

import { fullAddress } from '../../../helpers/full-address';
import { module, test } from 'qunit';

module('Unit | Helper | full address');

test('it works', function(assert) {
  var line1 = "123 Test Street";
  var town = "My Town";
  var postCode = "TE5 5ST";

  var expected = line1 + ", " + town + ", " + postCode;

  var result = fullAddress(null, {
    line1: line1,
    town: town,
    postCode: postCode
  }); // Call helper here

  assert.equal(result, expected);
});

如果你只运行这个测试模块,你会得到:

测试截图

fullAddress在这种情况下,返回值为:123 Test Street, My Town, TE5 5ST与预期值匹配的值。

于 2015-06-17T13:18:35.770 回答