Glyoko
Glyoko

Reputation: 2090

How can I add properties to a component in a unit test before init?

I'm working on an Ember component with an init function that I'd like to add a unit test for. The component has the following properties:

1) The init function must not be run more than once, and

2) The component depends on having a model (currentUser) passed to it.

So far I have tried writing a test like this:

test('#init', function(assert) {
  const component = this.owner.lookup('component:component-that-depends-on-property');

  const currentUser = make('user');
  component.set('currentUser', user);

  component.init();

  assert.ok(component.somethingHasHappened);
});

My problem is that init method is run on the owner.lookup line, meaning I have no way of getting the currentUser into the component before it runs. Again, I cannot run the init method more than once without blowing up the component's state.

I noticed that the lookup method takes an options argument and thought I might be able to use that to pass currentUser in, but that doesn't seem to work and I couldn't find much documentation on the lookup method.

I'd like to avoid writing an integration test for this, if possible. Is there a good way of doing this/workaround I'm not seeing?

Upvotes: 1

Views: 488

Answers (2)

Patrick Berkeley
Patrick Berkeley

Reputation: 2286

If you do unit test the component, you can do:

const component = this.owner.factoryFor('component:component-that-depends-on-property').create({
  currentUser: user,
});

That will create an instance of your component with currentUser set. You will not need to call init() explicitly because it is called on create().

Upvotes: 1

prat_bhan
prat_bhan

Reputation: 139

I would suggest writing integration tests for components. Avoid writing unit test cases for components rather write unit test cases for controllers, mixins, models, routes, services

Upvotes: 2

Related Questions