Testing route with unauthenticatedRouteMixin fails with "Promise rejected before it exists" - ember.js

THE ROUTE
import Ember from "ember";
import UnauthenticatedRouteMixin from 'ember-simple-auth/mixins/unauthenticated-route-mixin';
const {
Route,
} = Ember;​
export default Route.extend(UnauthenticatedRouteMixin, {
});
THE TEST
import { moduleFor, test } from 'ember-qunit';​
moduleFor('route:index', 'Unit | Route | index', {});
test('it exists', function(assert) {
var route = this.subject();
assert.ok(route);
});
THE ERROR
Promise rejected before it exists: Could not find module `ember-simple-auth/mixins/unauthenticated-route-mixin` imported from `appname/routes/index`
Ember: 1.13.15
Ember Simple Auth: 1.0.1
It is just the standard test generated by ember but fails everytime.
Thank you for any help

Related

How to setup ember-intl service in Ember integration tests?

I have just begun adding ember-intl into an application for which I had working tests. My acceptance tests are still working, but my integration tests on components whose templates are using ember-intl for string translation are failing with:
"No locale defined. Unable to resolve translation:..."
In the ember-intl docs there is a section on Integration Testing, which seems to be out of date:
import hbs from 'htmlbars-inline-precompile';
import wait from 'ember-test-helpers/wait';
import { moduleForComponent, test } from 'ember-qunit';
let service;
moduleForComponent('x-product', 'XProductComponent', {
integration: true,
setup() {
service = this.container.lookup('service:intl');
service.setLocale('en-us');
}
});
test('it renders', function(assert) {
assert.expect(1);
this.render(hbs`{{x-product price=price deadline=deadline}}`);
this.set('price', 1000);
this.set('deadline', new Date());
let output = this.$().text();
assert.ok(output);
});
test('it translates', function(assert) {
assert.expect(1);
/* waits for async behavior (loading translations on app boot) to settle */
return wait().then(() => {
assert.equal(service.t('some.key'), 'Hello world');
});
});
I've looked in the Ember docs and I can see how to stub a service for testing, but not how to just load the service in a test and then work with it.
Instead of using this.container, we now need to use this.owner in the new format tests. Here's a snippet of code showing how to use it in context:
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { find, render } from '#ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
module('Integration | Component | login-form', function(hooks) {
setupRenderingTest(hooks);
let service;
hooks.beforeEach(function() {
service = this.owner.lookup('service:intl');
service.setLocale('en-us');
});
test('it renders', async function(assert) {
await render(hbs`{{login-form}}`);
assert.equal(find('[data-test-login-title]').textContent.trim(), 'Login');
});
});
A PR has been submitted to ember-intl, so hopefully the docs will reflect the latest best-practice soon.

Mirage responds 404 on acceptances tests

I've been struggling with mirage for the past few days, and still haven't come up with a solution.
Even with a very simplified configuration (see below), mirage responds with a 404 error code whenever it is called within acceptance tests.
The calls do work perfectly when I serve my app and look at the browser console
(Mirage responds with a 200 status, and the data is here with the hello#world.com that I setup bellow).
Here's my mirage/config.js file
// mirage/config.js
export default function() {
this.get('/users', function() {
return {
data: [{
type: 'user',
id: 'first',
attributes: {
email: 'hello#world.com'
}
}]
};
});
}
Here's my app/routes/home.js
// app/routes/home.js
import Route from '#ember/routing/route';
export default Route.extend({
model() { return this.store.findAll('user'); }
});
Here's the failing test
import { module, test } from 'qunit';
import { visit, currentURL } from '#ember/test-helpers';
import { setupApplicationTest } from 'ember-qunit';
module('Acceptance | home', function(hooks) {
setupApplicationTest(hooks);
test('visiting /home', async function(assert) {
await visit('/home');
assert.equal(currentURL(), '/home');
});
});
With this message:
Promise rejected during "visiting /home": Ember Data Request GET /users
returned a 404
Payload (Empty Content-Type)
Not found: /users# 152 ms
Source:
Error: Ember Data Request GET /users returned a 404
Payload (Empty Content-Type)
Not found: /users
at ErrorClass.EmberError
(http://localhost:7357/assets/vendor.js:24125:25)
at ErrorClass.AdapterError
(http://localhost:7357/assets/vendor.js:157167:15)
at new ErrorClass (http://localhost:7357/assets/vendor.js:157185:22)
at Class.handleResponse
(http://localhost:7357/assets/vendor.js:169227:18)
at ajaxError (http://localhost:7357/assets/vendor.js:169720:25)
at Class.hash.error
(http://localhost:7357/assets/vendor.js:169308:23)
at fire (http://localhost:7357/assets/vendor.js:3607:31)
at Object.fireWith [as rejectWith]
(http://localhost:7357/assets/vendor.js:3737:7)
at done (http://localhost:7357/assets/vendor.js:9646:14)
at XMLHttpRequest.<anonymous>
(http://localhost:7357/assets/vendor.js:9887:9)
Thank you
Are you sure Mirage is even running during your test?
If you're on a recent version of Ember, Mirage's default initializer may not be running. (This needs to be fixed.)
You might want to give the latest release notes a read, and make sure you're on version 0.4.2+.
In the new style of tests, you'll need to do something like
import { module, test } from 'qunit';
import { visit, currentURL } from '#ember/test-helpers';
import { setupApplicationTest } from 'ember-qunit';
+ import setupMirage from 'ember-cli-mirage/test-support/setup-mirage';
module('Acceptance | login', function(hooks) {
setupApplicationTest(hooks);
+ setupMirage(hooks);
test('visiting /login', async function(assert) {
await visit('/login');
assert.equal(currentURL(), '/login');
});
});

Ember CLI Simple Auth test helper authenticateSession is not defined

I am using ember-cli 0.2.6 and ember-cli-simple-auth 0.8.0-beta.2.
Starting from scratch I do the following:
ember create project1
//inside project1
ember install ember-cli-simple-auth
now i am adding the following line to tests/helpers/start-app:
import 'simple-auth-testing/test-helpers';
and in environment.js only add this:
if (environment === 'test') {
ENV['simple-auth'] = {
store: 'simple-auth-session-store:ephemeral'
};
...
}
Also I created an acceptance test named "login"
ember generate acceptance-test login
Which i adjusted to make use of the authenticateSession(); helper:
import Ember from 'ember';
import {
module,
test
} from 'qunit';
import startApp from 'project1/tests/helpers/start-app';
var application;
module('Acceptance: Login', {
beforeEach: function() {
application = startApp();
},
afterEach: function() {
Ember.run(application, 'destroy');
}
});
test('visiting /login', function(assert) {
authenticateSession();
ok('yes');
});
Now however, whenever i run ember test I get the same error message:
acceptance/login-test.js: line 22, col 3, 'authenticateSession' is not defined.
What did I miss to be not able to access the simple-auth helpers inside my acceptance test? I also tried with the simple-auth 0.7.3 release,... In another try I set up a custom authorizer, but got the same error.
You need to import the testing helpers like this:
import initializeTestHelpers from 'simple-auth-testing/test-helpers';
initializeTestHelpers();

Could not find the "presence" validator with Ember Validations addon

I'm trying to use the Ember Validations addon and I can't get it working. In the Chrome console, I see: WARNING: Could not find the "presence" validator.
Here is my model:
import Ember from 'ember';
import DS from 'ember-data';
import EmberValidations from 'ember-validations';
export default DS.Model.extend(EmberValidations.Mixin, {
name: DS.attr('string'),
validations: {
name: {
presence: true
}
}
});
And here is the my test:
import Ember from 'ember';
import EmberValidations from 'ember-validations';
import { moduleForModel, test } from 'ember-qunit';
moduleForModel('person', 'Unit | Model | person', {
// Specify the other units that are required for this test.
needs: ['ember-validations#validator:local/presence'],
afterEach: function() {
window.sessionStorage.clear();
}
});
test('isValid should be false if name is not set', function(assert) {
stop();
var model = this.subject();
console.log(model);
Ember.run(function() {
sinon.spy(model, 'save');
model.validate().then(function() {
start();
assert.equal(model.get('isValid'), false);
});
});
});
The result of this test is:
Died on test #1 at Object.test (http://localhost:4200/assets/test-support.js:1644:11)
at http://localhost:4200/assets/myproj.js:14450:15
at mod.state (http://localhost:4200/assets/vendor.js:150:29)
at tryFinally (http://localhost:4200/assets/vendor.js:30:14)
at requireModule (http://localhost:4200/assets/vendor.js:148:5)
at Object.TestLoader.require (http://localhost:4200/assets/test-loader.js:29:9)
at Object.TestLoader.loadModules (http://localhost:4200/assets/test-loader.js:21:18): <(unknown mixin):ember848>
You need to add dependencies to test suite as defined in ember-validations docs in testing part. However, take notice that these docs are a little bit outdated. The proper needs should include only the validators you use (presence) and look like this:
needs: ['ember-validations#validator:local/presence']
Do not indclude service:validations.
I posted an issue quite a while ago but it's not discussed yet.

Ember-cli : relationship unit test for model failing

I am using Ember-cli and qunit for testing.
Item Model
import DS from 'ember-data';
var attr = DS.attr,
belongsTo = DS.belongsTo;
export default DS.Model.extend({
offer: belongsTo('offer'),
});
Here am adding test for relation between item and Offer model.
Item Tests
import Ember from "ember";
import DS from "ember-data";
import { test, moduleForModel } from 'ember-qunit';
moduleForModel('item', 'Item Model', {
needs: ['model:item']
});
test('offer relationship', function() {
var relationships = Ember.get(App.Item, 'relationships');
deepEqual(relationships.get(App.Offer), [
{ name: 'offer', kind: 'belongsTo' }
]);
});
Error Trace:
Died on test #1 at test (http://localhost:4200/assets/vendor.js:73836:13)
at eval (goodcity/tests/unit/item-test.js:44:5)
at requireModule (http://localhost:4200/assets/vendor.js:54:29)
at http://localhost:4200/assets/test-loader.js:14:29: App is not defined
Source:
ReferenceError: App is not defined
at Object.eval (goodcity/tests/unit/item-test.js:45:37)
at Object.wrapper (http://localhost:4200/assets/vendor.js:73824:31)
at Object.Test.run (http://localhost:4200/assets/qunit.js:203:18)
at http://localhost:4200/assets/qunit.js:361:10
at process (http://localhost:4200/assets/qunit.js:1453:24)
at http://localhost:4200/assets/qunit.js:479:5
Am i missing something?
I'm just now in the process of converting over an older Ember App to the new ember-cli and ran into a similar situation. Since Ember CLI uses ES6 module syntax you can't access anything directly on the App object.
You will need to import your objects from their respective model files.
import Item from "<modulePrefix>/models/item";
import Offer from "<modulePrefix>/models/offer";
Second, your moduleForModel('item') should have needs: ['model:offer'].
Here's a passing a test using the provided files. (I used: ember new stackoverflow)
import Ember from "ember";
import { test, moduleForModel } from 'ember-qunit';
/* Import Models */
import Item from "stackoverflow/models/item";
import Offer from "stackoverflow/models/offer";
moduleForModel('item', 'Item', {
// Item needs the offer model.
needs: ['model:offer']
});
test('offer relationship', function() {
/* For some reason this was necessary to prime the store. */
/* Without this line I get the error:
'undefined' is not an object (evaluating 'store.modelFor') */
var model = this.subject();
/* App.Item -> Item, App.Offer -> Offer */
var relationships = Ember.get(Item, 'relationships');
deepEqual(relationships.get(Offer), [
{ name: 'offer', kind: 'belongsTo' }
]);
});