How do i access a shorthand helper in Ember in a unit test?

80 views Asked by At

How do I access a shorthand helper in a unit test in order to test it?

Example:

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

Use the shorthand helper in 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}}

full-address-test

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

How would I call the shorthand helper with those 3 variables that are hashed?

1

There are 1 answers

2
Daniel On BEST ANSWER

You need to slightly modify your helper file:

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

Then, you can write your test:

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

If you run this test module only you will get:

test screenshot

Return value of fullAddress in this case was: 123 Test Street, My Town, TE5 5ST which matched expected value.