WantToCodeMore
WantToCodeMore

Reputation: 21

Ember-Data Unit Testing Store

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>

Upvotes: 1

Views: 1969

Answers (1)

Mikko Paderes
Mikko Paderes

Reputation: 840

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);
});

Upvotes: 2

Related Questions