I'm trying to write an acceptance test to see if a certain property in the model for the route I visit equals what I am asserting.
I am not outputting information to the page with this route, instead I will be saving some portion of it to localstorage using an ember addon. So normally I realize I could use a find() to find an element on the page and check it's content to determine if the model is being resolved but that won't work for this case.
In the acceptance test I have this setup (using mirage btw)
test('Returns a user', function(assert) {
// Generate a user
var user = server.create('user',{first_name: 'Jordan'});
// Visit the index page with the users short_url
visit('/' + user.short_url);
var route = this.application.__container__.lookup('route:index');
// Assert that the model the user we created by checking the first name we passed in
assert.equal(route.model.first_name,'Jordan','Model returns user with first name Jordan');
});
But when I run the test it shows the result as being undefined
UPDATE:
After trying Daniel Kmak's answer I still cannot get it to pass. This is the route code I am working with
import Ember from 'ember';
import LocalUser from 'bidr/models/user-local';
export default Ember.Route.extend({
localUser: LocalUser.create(),
navigationService: Ember.inject.service('navigation'),
activate() {
this.get('navigationService').set('navigationMenuItems', []);
},
beforeModel() {
this.localUser.clear();
},
model(params) {
var self = this;
return this.store.queryRecord('user',{short_url: params.short_url}).then(function(result){
if(result){
self.set('localUser.user', {
"id": result.get('id'),
"first_name": result.get('first_name'),
"active_auction": result.get('active_auction'),
"phone": result.get('phone')
});
// transition to event page
self.transitionTo('items');
} else {
self.transitionTo('home');
}
});
}
});
And the test looks like this
import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from 'bidr/tests/helpers/start-app';
module('Acceptance | index route', {
beforeEach: function() {
this.application = startApp();
},
afterEach: function() {
Ember.run(this.application, 'destroy');
}
});
test('Returns a user', function(assert) {
var user = server.create('user',{first_name: 'Jordan'});
visit('/' + user.short_url);
var route = this.application.__container__.lookup('route:index');
andThen(function() {
assert.equal(route.get('currentModel.first_name'),'Jordan','Model returns user with first name Jordan');
});
});
All the code works as it should in development.
Ok, so I've experimented with testing in Ember and it seems you should be good with getting model in andThen hook:
test('returns a user', function(assert) {
visit('/'); // visit your route
var route = this.application.__container__.lookup('route:index'); // find your route where you have model function defined
andThen(function() {
console.log(route.get('currentModel')); // your model value is correct here
assert.equal(currentURL(), '/'); // make sure you've transitioned to correct route
});
});
Taking your code it should run just fine:
test('Returns a user', function(assert) {
var user = server.create('user',{first_name: 'Jordan'});
visit('/' + user.short_url);
var route = this.application.__container__.lookup('route:index');
andThen(function() {
assert.equal(route.get('currentModel.first_name'),'Jordan','Model returns user with first name Jordan');
});
});
Another thing to note is that you can access model via route.currentModel property.
For my model:
export default Ember.Route.extend({
model() {
return Ember.RSVP.hash({
simple: 'simpleValue',
promise: Ember.RSVP.resolve(5)
});
}
});
In andThen with console.log(route.get('currentModel')); I got:
Object {simple: "simpleValue", promise: 5}
Logged.
Related
My ember version:
DEBUG: -------------------------------
Ember : 2.10.2
Ember Data : 2.11.0
jQuery : 2.2.4
Ember Simple Auth : 1.1.0
Model Fragments : 2.3.2
DEBUG: -------------------------------
And my route code:
import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
import RSVP from 'rsvp';
export default Ember.Route.extend(AuthenticatedRouteMixin, {
model() {
console.log(1);
return RSVP.hash({
...,
user: this.store.findRecord('user', this.get('session.data.authenticated.id'))
});
},
afterModel(model, transition) {
return this.store.findRecord('company', model.user.get('companyId')).then(company => {
console.log(2);
this.set('company', company);
});
},
setupController(controller, model) {
console.log(3);
controller.set('user', model.user);
controller.set('company', this.get('company'));
}
});
Look at console.log code, I think the correct order should be 1->2->3. But sometimes it turns out to be 1->3->2.
But my company id must come from user api. So what is way I set it in route? Thanks.
I am writing just another solution, From RSVP.hash api docs
Returns a promise that is fulfilled when all the given promises have been fulfilled, or rejected if any of them become rejected. The returned promise is fulfilled with a hash that has the same key names as the promises object argument. If any of the values in the object are not promises, they will simply be copied over to the fulfilled object.
So you can write your requirement like the below code,
model() {
var promises = {
user: this.store.findRecord('user', this.get('session.data.authenticated.id'))
};
return Ember.RSVP.hash(promises).then(hash => {
//then method will be called once all given promises are fulfilled, or rejected if any of them become rejected.
return this.store.findRecord('company', hash.user.get('companyId')).then(company => {
hash.company = company; // Here i am setting company property inside model itself, so you dont need to set it in route and carry over to controller
return hash;
});
})
}
Note:I am curious to know if you can reproduce 1->3->2 behavior in ember-twiddle.
Actually the right way to do this is to put all your model fetching in your model hook:
model() {
return RSVP.hash({
...,
user: this.store.findRecord('user', this.get('session.data.authenticated.id'))
}).then(hash => {
hash.company = this.store.findRecord('company', hash.user.get('companyId'));
return RSVP.hash(hash);
})
},
setupController(controller, model) {
controller.set('user', model.user);
controller.set('company', model.company);
}
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>
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);
});
How do I access the current model? I am aware of application.__container_.lookup but I understand this is a bit of a hack.
import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from 'myapp/tests/helpers/start-app';
let application;
module('Acceptance | booking/edit', {
beforeEach: function() {
application = startApp();
},
afterEach: function() {
Ember.run(application, 'destroy');
}
});
test('visiting /booking/edit', function(assert) {
visit('/booking/1');
//At this point I would like to access the model returned from the route model hook.
andThen(function() {
assert.equal(currentURL(), '/booking/1');
});
});
Sample Route excerpt.
this.route('booking', { path:'/booking' }, function() {
this.route('edit', { path:'/:booking_id' }, function() {
this.route('account', { path:'/account' });
...
});
...
});
You should be able to use moduleFor and then within the test you can use this.subject() to access the controller.
moduleFor('controller:bookingsEdit', 'Bookings Edit Controller');
If moduleFor is undefined. Then import moduleFor import {moduleFor} from 'ember-qunit';
and then within the test you can use this.subject() to access the controller
moduleFor(fullName [, description [, callbacks]])
fullName: (String) - The full name of the unit, ie
controller:application, route:index.
description: (String) optional - The description of the module
callbacks: (Object) optional - Normal QUnit callbacks (setup and
teardown), with addition to needs, which allows you specify the other
units the tests will need.
http://guides.emberjs.com/v1.10.0/testing/testing-controllers/
https://github.com/rwjblue/ember-qunit
I can't find a single example in google for unit test of views in Ember CLI that renders the view (without renders all app).
I wanna this for test events registered inside of didInserElement hook.
For components i can find docs very easy. For render the component in a test with moduleForComponent just do:
test("component test", function(){
var component = this.subject(),
element = this.append();
ok(element.is('.clickable'), 'has the clickable class');
});
But how i do this for views?
I use this way to render only the view in unit tests:
One important thing to note, is that you need to needs all templates, partials and helpers explicitly. Otherwise the test will fail due to lookup errors.
tests/unit/views/main-test.js:
import Ember from 'ember';
import { test, moduleFor } from 'ember-qunit';
var view;
moduleFor('view:main', 'MainView', {
needs: ['template:main'], // won't find the 'main' template without this
setup: function() {
var controller = Ember.ObjectController.extend({
//mockController if needs
}).create();
view = this.subject({
controller: controller,
templateName: 'main',
});
Ember.run(function() {
view.appendTo('#ember-testing');
});
},
teardown: function() {
Ember.run(function() {
view.destroy();
});
},
});
test("didInsertElement", function(){
var element = Ember.$('.main');
var controller = view.get('controller');
var eventForPressCtrlAltM = Ember.$.Event( "keydown", { which: 77, altKey: true, ctrlKey: true } );
Ember.run(function() {
element.trigger(eventForPressCtrlAltM);
});
strictEqual(/* ... */);
});
I am following a Dockyard Tutorial on using ember-cli with rails. This particular section is on basic integration testing. Unfortunately, it doesn't seem to be registering properly (at least I don't think so). The test should fail and say something along the lines of "Expected: 'Welcome to Boston Ember'"; rather, it says "should pass jshint" which it is and is therefore passing. Any idea what I am doing wrong?
tests/integration/landing-page-test.js
import Ember from 'ember';
import startApp from 'bostonember/tests/helpers/start-app';
var App;
module('Integration - Landing Page', {
setup: function() {
App = startApp();
},
teardown: function() {
Ember.run(App, 'destroy');
}
});
test('Should welcome me to Boston Ember', function() {
visit('/').then(function() {
equal(find('h2#title').text(), 'Welcome bloopde bloopasa to Boston Ember');
});
});
tests/helpers/start-app.js
/* global require */
var Application = require('bostonember/app')['default'];
var Router = require('bostonember/router')['default'];
import Ember from 'ember';
export default function startApp(attrs) {
var App;
var attributes = Ember.merge({
// useful Test defaults
rootElement: '#ember-testing',
LOG_ACTIVE_GENERATION:false,
LOG_VIEW_LOOKUPS: false
}, attrs); // but you can override;
Router.reopen({
location: 'none'
});
Ember.run(function(){
App = Application.create(attributes);
App.setupForTesting();
App.injectTestHelpers();
});
App.reset(); // this shouldn't be needed, i want to be able to "start an app at a specific URL"
return App;
}
Will provide additional info upon request. Thank you!
Must have just been a hiccup?
Solution was to recreate the file, same code, but works now.