All files / addon-test-support/macros getter.js

100% Statements 5/5
100% Branches 2/2
100% Functions 1/1
100% Lines 5/5

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59    1x                                                                                       36x       42x 6x     36x        
import { throwBetterError } from '../-private/better-errors';
 
const NOT_A_FUNCTION_ERROR = 'Argument passed to `getter` must be a function.';
 
/**
 * Creates a Descriptor whose value is determined by the passed-in function.
 * The passed-in function must not be bound and must not be an arrow function,
 * as this would prevent it from running with the correct context.
 *
 * @example
 *
 * // <input type="text">
 * // <button disabled>Submit</button>
 *
 * import { create, value, property } from 'ember-cli-page-object';
 * import { getter } from 'ember-cli-page-object/macros';
 *
 * const page = create({
 *   inputValue: value('input'),
 *   isSubmitButtonDisabled: property('disabled', 'button'),
 *
 *   // with the `getter` macro
 *   isFormEmpty: getter(function() {
 *     return !this.inputValue && this.isSubmitButtonDisabled;
 *   }),
 *
 *   // without the `getter` macro
 *   _isFormEmpty: {
 *     isDescriptor: true,
 *     get() {
 *       return !this.inputValue && this.isSubmitButtonDisabled;
 *     }
 *   }
 * });
 *
 * // checks the value returned by the function passed into `getter`
 * assert.ok(page.isFormEmpty);
 *
 * @public
 *
 * @param {Function} fn - determines what value is returned when the Descriptor is accessed
 * @return {Descriptor}
 *
 * @throws Will throw an error if a function is not passed in as the first argument
 */
export function getter(fn) {
  return {
    isDescriptor: true,
 
    get(key) {
      if (typeof fn !== 'function') {
        throwBetterError(this, key, NOT_A_FUNCTION_ERROR);
      }
 
      return fn.call(this, key);
    }
  };
}