2

I'm using a custom test helper which requires access to the Ember data store, but I don't know how to access it from the given application argument.

export default registerAsyncHelper('myCustomHelper', function(app) {
  console.log(app); // how to access store?
  let store = app.__registry__.registrations['service:store'];
  store.pushPayload(// json payload);
});

How can I get access to the store when registering a custom helper? I've been trying to figure out a way to access it from the __registry__.registrations['service:store'] key but that gives me an undefined value, when I can see that it's there and has the pushPayload function. Help would be greatly appreciated

NullVoxPopuli
  • 61,906
  • 73
  • 206
  • 352
a7omiton
  • 1,597
  • 4
  • 34
  • 61

2 Answers2

2

Hah! I think I got it:

export default registerAsyncHelper('myCustomHelper', function(app) {
  let instance = app.buildInstance();
  let store = instance.lookup('service:store');
  store.pushPayload(// json payload);
});

Not sure if that has any side effects though? Please let me know if it does, I think I've spent enough time trying to setup a good test environment already :p

a7omiton
  • 1,597
  • 4
  • 34
  • 61
2

This is typescript, but it should hopefully work the same in js (without the type annonations though)

// tests/helpers/get-service.ts
import { getContext } from "@ember/test-helpers";

export function getService<T>(name: string): T {
  const { owner } = getContext();

  const service = owner.lookup(`service:${name}`);

  return service;
}

example usage:

// tests/helpers/create-current-user.ts
import { run } from '@ember/runloop';
import { DS } from 'ember-data';

import Identity from 'emberclear/data/models/identity/model';

import { getService } from './get-service';

export async function createCurrentUser(): Promise<Identity> {
  const store = getService<DS.Store>('store');

  const record = store.createRecord('identity', {
    id: 'me', name: 'Test User'
  });

  await record.save();

  return record;
}

this code is from https://emberclear.io https://gitlab.com/NullVoxPopuli/emberclear/tree/master/packages/frontend/tests/helpers

hope this helps :)

NullVoxPopuli
  • 61,906
  • 73
  • 206
  • 352