简体   繁体   中英

Using fixtures in Ember with the LocalStorage adapter

I'm building an Ember app which uses the LocalStorage adapter for saving and retrieving models, but it would be very convenient to be able to preload some models into the app when testing. The standard way seems to be switching out the app's normal storage adapter in favor of the FixtureAdapter but I'm uncomfortable testing against an app whose configuration is so different from how the app will run in production. I'd much prefer to keep the LocalStorage adapter in place for tests so that I'm testing with real store behavior.

Here's my store definition:

App.ApplicationSerializer = DS.LSSerializer.extend();
App.ApplicationAdapter = DS.LSAdapter.extend({
    namespace: 'App'
});
App.store = DS.Store.extend();

I've tried to preload my models manually like this:

App.store.push(
    "myModel", {
      id: 1,
      someProperty: "a"
 });

but all I get is "Cannot read property 'push' of undefined", which tells me I'm going about this all wrong. Is there any way to preload models into an Ember app using an adapter other than the FixtureAdapter? Or maybe use the FixtureAdapter side-by-side with another adapter?

The store is initialized by an initializer. App.store in your particular case is a class definition, not an instance, not that you'd want to use that pattern anyway.

App.initializer({
    name:'fixtureInjector',
    after:['store'],

    initialize: function (container, application) {
        var store = container.lookup('store:main');
        store.push("myModel", {
          id: 1,
          someProperty: "a"
        });
    }
});

Example: http://emberjs.jsbin.com/OxIDiVU/882/edit

You could also do this in the application route if you didn't feel like using the container/initializer.

App.ApplicationRoute = Em.Route.extend({
  beforeModel: function(){
    this.store.push("myModel", {
      id: 1,
      someProperty: "a"
    });
  }
});

May be a little off topic but I wanted to pre-seed localstorage data and then use the persisted data if it the seeded data was modified in anyway. I opted to use a simple beforeModel hook. For example see below for a simple todolist:

import Ember from 'ember';

export default Ember.Route.extend({
  beforeModel(){
    this.store.findAll('todo').then((data)=> {
      if (data.get('length') == 0) {
        this.store.createRecord('todo',{title: 'get milk',isComplete:     false}).save();
        this.store.createRecord('todo',{title: 'pick up clothes',isComplete: false}).save();
        this.store.createRecord('todo',{title: 'be amazing',isComplete: false}).save();
      }
    })
  },
  model(){
    return this.store.findAll('todo');
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM