Using an initializer in an unit test? - unit-testing

I have a stdlib initializer. In that initializer, i reopen some of built-in Ember classes and add some custom methods. For example, i added reverseEach to Ember.Enumerable and Array.
They work fine in the app, but in tests i receive "reverseEach: undefined is not a function".
How do i indicate that the test should use the initializer?
I tried needs: [..., 'initializer:stdlib']. It does not stumble upon that, but i still receive the "undefined" error.
Here's an example test:
`import { test, moduleForModel } from 'ember-qunit'`
moduleForModel 'foo', 'foo',
needs: [
'model:bar'
'initializer:stdlib'
]
test 'deleteLastNItems', ->
model = #subject()
model.set '', ['foo', 'bar', 'baz', 'quux']
model.deleteLastNItems 2 # This should not die with "reverseEach: undefined is not a function"
deepEquals model.get('someProperty'), ['foo', 'bar']

You can use ember g initializer stdlib, it will generate sample code for you, including test.
import Ember from 'ember';
import { initialize } from '../../../initializers/stdlib';
import { module, test } from 'qunit';
var registry, application;
module('Unit | Initializer | stdlib', {
beforeEach: function() {
Ember.run(function() {
application = Ember.Application.create();
registry = application.registry;
application.deferReadiness();
});
}
});
// Replace this with your real tests.
test('it works', function(assert) {
initialize(registry, application);
// you would normally confirm the results of the initializer here
assert.ok(true);
});
Refer: Ember blueprints

Related

how to write a unit test for controller action with promises in emberjs

I have a ember js controller with the following action that takes a model.
How do I write a unit test to test the action which returns a promise?
deleteUser(model)
{
model.destroyRecord().then(() => this.transitionToRoute('posts'));
}
The wait() function sounds like what you want here. Not sure it works with promises, as it does not mention promises in this part of the documentation. Might want to give it a shot anyway.
From the Ember docs (https://guides.emberjs.com/v2.12.0/testing/testing-components/):
import { moduleForComponent, test } from 'ember-qunit';
import wait from 'ember-test-helpers/wait';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('delayed-typeahead', 'Integration | Component | delayed typeahead', {
integration: true
});
const stubResults = [
{ name: 'result 1' },
{ name: 'result 2' }
];
test('should render results after typing a term', function(assert) {
assert.expect(2);
this.set('results', []);
this.set('fetchResults', (value) => {
assert.equal(value, 'test', 'fetch closure action called with search value');
this.set('results', stubResults);
});
this.render(hbs`{{delayed-typeahead fetchResults=fetchResults results=results}}`);
this.$('input').val('test');
this.$('input').trigger('keyup');
return wait().then(() => {
assert.equal(this.$('.result').length, 2, 'two results rendered');
});
});
EDIT: The example above is from integration tests... not sure this is what you have in mind. Note, there is also the andThen helper which you may want to look into. Perhaps give us some more information regarding what you have in mind?

How to unit test custom Ember.Inflector rules

I'm trying to create a test for the following initializer:
import Ember from 'ember';
const { Inflector } = Ember;
export function initialize() {
Inflector.inflector.uncountable('settings');
Inflector.inflector.uncountable('feedback');
}
export default {
name: 'inflector',
initialize
};
Ember-cli generates the following test for an initializer:
import Ember from 'ember';
import InflectorInitializer from 'redirect/initializers/inflector';
import { module, test } from 'qunit';
let application;
module('Unit | Initializer | inflector', {
beforeEach() {
Ember.run(function() {
application = Ember.Application.create();
application.deferReadiness();
});
}
});
test('it works', function(assert) {
InflectorInitializer.initialize(application);
assert.ok(true);
});
As I understand it, a beforeEach() hook creates an application first, and then pauses it so the initializer test can run.
The test fails because Ember.Inflector in undefined when the initializer is called by the test.
How do I test custom inflector rules?
I'd like to have the following assertions:
assert.equal(inflector.singularize('settings'), 'settings');
assert.equal(inflector.pluralize('settings'), 'settings');
assert.equal(inflector.singularize('feedback'), 'feedback');
assert.equal(inflector.pluralize('feedback'), 'feedback');
assert.equal(inflector.rules.uncountable['settings'], true);
assert.equal(inflector.rules.uncountable['feedback'], true);
I'd be willing to configure inflector rules in a different way if this will make it testable.
I tried to create an application and remove deferReadiness to then see If I can put those assertions in the test. But even though Ember.Inflector is then defined, it doesn't contain my custom rules.

Import { module } from 'ember-qunit'

Looking over the Ember CLI docs, it says to create an integration test like so:
import Ember from "ember";
import { module, test } from 'ember-qunit';
import startApp from '../helpers/start-app';
var App;
module('An Integration test', {
beforeEach: function() {
App = startApp();
},
afterEach: function() {
Ember.run(App, App.destroy);
}
});
test("Page contents", function(assert) {
assert.expect(2);
visit('/foos').then(function() {
assert.equal(find('.foos-list').length, 1, "Page contains list of models");
assert.equal(find('.foos-list .foo-item').length, 5, "List contains expected number of models");
});
});
The problem is, this code results in:
TypeError: undefined is not a function
If I remove the test, I still get that error. If I remove the module, then I don't get the error. (But neither does qunit run the test.) This makes sense, because it looks like ember-qunit doesn't export a module.
So what am I suppose to do here?

"Attempting to register an unknown factory" in model test

I have these models in an ember-cli app:
var PuzzleRound = DS.Model.extend({
year: DS.attr('number')
});
var Puzzle = DS.Model.extend({
puzzleRounds: DS.hasMany('puzzleRound', {async: true})
});
And here's my test from tests/unit/models/puzzle-test.js:
import {
moduleForModel,
test
} from 'ember-qunit';
import PuzzleRound from 'weather-roulette/models/puzzle-round';
moduleForModel('puzzle', 'Puzzle', {
// Specify the other units that are required for this test.
needs: ['model:puzzleRound']
});
test('it exists', function() {
var model = this.subject();
// var store = this.store();
ok(!!model);
});
I get this error when running ember test:
Attempting to register an unknown factory: `model:puzzleRound`
I'm using ember-cli 0.1.1, Ember.js 1.7.0, Ember Data 1.0.0-beta.11. Does anyone have anything I can try to fix this?
I just tried out this code with ember-cli 0.0.44 and I got the same error that you did.
I renamed both references to the puzzleRound model path to puzzle-round and then your test passed for me. So:
DS.Model.extend({
puzzleRounds: DS.hasMany('puzzle-round', {async: true})
});
and
moduleForModel('puzzle', 'Puzzle', {
needs: ['model:puzzle-round']
});
I knew that the hyphenated style was preferred over the camelCase style, but I'm not sure when this became mandatory. This requirement may be specific to ember-cli or ember-qunit.
I was looking for a solution similar to this one for awhile, and did not see any mention of my solution so I thought I would post here anyways. It's quite simple really: make sure that the controller you're referencing is actually there.
// my-ember-application/tests/unit/controllers/index/bar-test.js
moduleFor('controller:index/bar', 'My Bar Test', {
beforeEach() { .. }
});
test('it exists', function (assert) {
assert.ok(true);
});
This code would reference a controller at this location:
my-ember-application/app/controllers/index/bar.js

Ember.js - Integration Testing with Ember-CLI

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.