1

What is the best way to test a model's store? I am using ember-data 2.7.0 and would like to test that I can create a model instance and save it to the backend (firebase) successfully.

I have wrapped the var record = store.create and record.save in and Ember.run function but I get You can only unload a record which is not inFlight. `<(subclass of DS.Model):ember227:null>

  • You don’t need to use ember data in unit tests to create records. You can mock store to return the Ember.Object with same attributes as your model. – Bishnu Rawal Sep 21 '16 at 07:17
  • I don't disagree in practice. I think what I am really getting at is a good way to test and make sure I have my models configured correctly to generate the right end points. – WantToCodeMore Sep 22 '16 at 03:22

1 Answers1

2

Lots of way to test this but the one that I prefer is through spying/stubbing using ember-sinon.

Assuming you have this action for creating and saving a record:

import Route from 'ember-route';

export default Route.extend({
  actions: {
    createAndSaveTheRecord() {
      this.store.createRecord('dummy_model', {
        id: 'dummy',
        name: 'dummy'
      }).save();
    }
  }
});

You can have a test that looks like this:

import sinon from 'sinon';

test('should create a record', function(assert) {
  assert.expect(1);

  // Arrange
  let stub = sinon.stub().returns({save: sinon.stub()});
  let route = this.subject({store: {createRecord: stub}});

  // Act
  route.send('createAndSaveTheRecord');

  // Assert
  assert.ok(stub.calledWith('dummy_model', {id: 'dummy', name: 'dummy'}));
});

test('should save the created record', function(assert) {
  assert.expect(1);

  // Arrange
  let spy = sinon.spy();
  let route = this.subject({
    store: {
      createRecord: sinon.stub().returns({
        save: spy
      })
    }
  });

  // Act
  route.send('createAndSaveTheRecord');

  // Assert
  assert.ok(spy.calledOnce);
});
Mikko Paderes
  • 830
  • 9
  • 18