Skip to content

Instantly share code, notes, and snippets.

@snewcomer
Last active October 30, 2020 03:38
Show Gist options
  • Select an option

  • Save snewcomer/589bcf6361e0ddf9d0f564c7042c6f87 to your computer and use it in GitHub Desktop.

Select an option

Save snewcomer/589bcf6361e0ddf9d0f564c7042c6f87 to your computer and use it in GitHub Desktop.
ember-unit-testing-components.js
// test helper
import { getContext } from '@ember/test-helpers';
export default function createComponent(lookupPath, named = {}) {
let { owner } = getContext();
let componentManager = owner.lookup('component-manager:glimmer');
let { class: componentClass } = owner.factoryFor(lookupPath);
return componentManager.createComponent(componentClass, { named });
}
// In your test
const component = createGlimmerComponent('component:my-component');
assert.equal(
component.getId(stuff),
'expectedId',
'returns expected id'
);
@snewcomer
Copy link
Author

snewcomer commented Oct 30, 2020

Why components, in many cases, should avoid unit testing.

From Ben Demboski

...Components don't really have a Javascript API. Like, no Javascript code besides Ember/glimmer internals should ever have a reference to the component object. So the API it makes the most sense to test is the one exposed via the DOM/templates, and then interactions with services via injections, which are fully available using rendering tests.

The advice that I've heard is that if you have any really in-depth logic that is isolated from the DOM/templates/arguments and from injected services, then you should put that in a utility function and unit test that utility function, because by definition it's not logic that is tightly coupled with the component-ness of your component.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment