Ember integration tests failing when running multiple at once - ember.js

I've run into a weird problem writing integration tests for my component. When I run each one individually, they pass. When I run multiple, the first one passes and the other ones fail. I think it has something to do with closure actions but I don't know.
Here's my component code
// components/game-nav-key.js
triggerKeyAction(code) {
if (this.get('prevKeyCode').contains(code)) {
this.sendAction('onPrevKey', true);
} else if (this.get('nextKeyCode').contains(code)) {
this.sendAction('onNextKey', true);
} else if (this.get('openKeyCode').contains(code)) {
this.sendAction('onOpenKey');
}
},
didInsertElement() {
var self = this;
Ember.$('body').keydown(function(e) {
self.triggerKeyAction(e.which);
});
Ember.$('body').keyup(function(e) {
});
}
And my tests
// game-nav-key-test.js
it('tracks key commands and sends an action for K', function() {
let spy = sinon.spy();
this.set('gotoPrev', spy);
this.render(hbs`
{{game-nav-key onPrevKey=(action gotoPrev)}}
`);
triggerKeydown($('body'), 75);
triggerKeyup($('body'), 75);
sinon.assert.calledOnce(spy);
sinon.assert.calledWith(spy, true);
});
it('tracks key commands and sends an action for J', function() {
let spy = sinon.spy();
this.set('gotoNext', spy);
this.render(hbs`
{{game-nav-key onNextKey=(action gotoNext)}}
`);
triggerKeydown($('body'), 74);
triggerKeyup($('body'), 74);
sinon.assert.calledOnce(spy);
sinon.assert.calledWith(spy, true);
});
it('tracks key commands and sends an action for R', function() {
let spy = sinon.spy();
this.set('open', spy);
this.render(hbs`
{{game-nav-key onOpenKey=(action open)}}
`);
triggerKeydown($('body'), 82);
triggerKeyup($('body'), 82);
sinon.assert.calledOnce(spy);
});
I removed all beforeEach's, so it's literally just those three tests. Like I said, each one passes individually, and when it is listed first, but the second two fail when run together. Note that using console.log statements I have verified that the code hits the line directly above each of the this.sendAction calls in their respective tests

seems you need to destroy your listeners created in didInsertElement
willDestroyElement() {
Ember.$('body').off('keydown');
Ember.$('body').off('keyup');
}

Related

Testing observable object angular 2 karma

I'm working on my unit test cases for Angular 2 with Karma, I got stuck with one of a function where I run the test for below line
expect(component.subscribeToEvents()).toBeTruthy();
and I view my coverage code, the lines inside the test file seems not covering anything inside the subscribe. I have tried using MockBackend in mocking the api call inside a function on service but I'm not sure how to do the mocking on a subscribed object, can somebody please help me?
The below is in test.component.ts
subscribeToEvents() {
this.subscription = this.czData.$selectedColorZone
.subscribe(items => {
this.resourceLoading = true;
if (!this.resourceData || (this.resourceData && this.resourceData.length === 0)) {
this.settings.layout.flypanel.display = false;
this.getAllResources(this.pagination.start, this.pagination.size);
}
else {
this.pagination.start = 1;
this.pagination.end = this.pagination.size;
this.getAllResources(1, this.pagination.size);
this.settings.layout.flypanel.display = true;
}
});
return true;
}
The screenshot of the coverage code
You can't do this, as the subscription is resolved asynchronously. So the synchronous test completes before the async task is resolved.
If all you want is coverage, you can just make the test async. This will cause the Angular test zone to wait until the async task is resolved, before completing the test
import { async } from '#angular/core/testing';
it('..', async(() => {
component.subscribeToEvents();
}))
You can't try to expect anything here, as there is no callback hook for when the task is resolved. So this is really a pointless test. It will give you coverage, but you aren't actually testing anything. For instance, you might want to test that the variables are set when the subscription is resolved.
Based on the code provided, what I would do instead is just mock the service, and make it synchronous. How can you do that? We you can make the mock something like
class CzDataSub {
items: any = [];
$selectedColorZone = {
subscribe: (callback: Function) => {
callback(this.items);
}
}
}
Then just configure it in the test
let czData: CzDataStub;
beforeEach(() => {
czData = new CzDataStub();
TestBed.configureTestingModule({
providers: [
{ provide: CzData, useValue: czData }
]
})
})
Now in your tests, you don't need to make it async, and you can provide any value you want by just setting the items property on the mock, and subscriber will get it
it('..', () => {
czData.items = something;
component.subscribeToEvents();
expect(component.settings.layout.flypanel.display).toBe(false);
})
UPDATE
I think I was half asleep when I wrote this post. One of the above statements is incorrect
You can't try to expect anything here, as there is no callback hook for when the task is resolved.
This is not completely true. This is what fixture.whenStable() is for. For instance if this is your service
class CzData {
_value = new Subject<>();
$selectedColorZone = this._value.asObservable();
setValue(value) {
this._value.next(value);
}
}
Then this is how you would make the test work
let czData: CzData;
let fixture: ComponentFixture<YourComponent>;
let component: YourComponent;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [ CzData ],
declarations: [ YourComponent ]
});
fixture = TestBed.createComponent(YourComponent);
component = fixture.componentInstance;
czData = TestBed.get(czData);
})
it('..', async(() => {
component.subscribeToEvents();
czData.setValue(somevalue);
fixture.whenStable().then(() => {
expect(component.settings.layout.flypanel.display).toBe(false);
})
}))
We use fixture.whenStable() to to wait for the async tasks to complete.
This is not to say that using the mock is wrong. A lot of the time, using the mock would be the way to go. I just wanted to correct my statement, and show how it could be done.
Consider how Angular Outputs are tested since they are subscribed to during testing: https://angular.io/guide/testing#clicking
it('should raise selected event when clicked (triggerEventHandler)', () => {
let selected: Hero;
comp.selected.subscribe((hero: Hero) => selectedHero = hero);
heroDe.triggerEventHandler('click', null);
expect(selectedHero).toBe(expectedHero);
});
So try:
const expectedItem = {}; // mock the expected result from 'subscribeToEvents'
it('should raise selected event when clicked (triggerEventHandler)', () => {
let selectedItem: any; // change to expected type
component.subscribeToEvents.subscribe((item: any) => selectedItem = item);
// fixture.detectChanges(); // trigger change detection if necessary here, depending on what triggers 'subscribeToEvents'
expect(selectedItem).toBe(expectedItem);
});

Running 2 asynchronous ember tests in the same test method

How do I run this in the same test? Right now I need to run them separately.
test('Props tests', function () {
var controller = this.subject({
model: createMock()
});
controller.set('foo', false);
controller.set('foo2', false);
equal(controller.get('baa'), true);
});
test('Props tests', function () {
var controller = this.subject({
model: createMock()
});
controller.set('foo', true);
controller.set('foo2', true);
equal(controller.get('baa2'), true);
});
I think I need to wrap some code in an Ember.run function statement.
In my experience, you should wrap your controller.sets in Ember.run.
Ember.run(function() {
controller.set('foo', false);
controller.set('foo2', false);
});
equal(controller.get('baa'), true);
You should be able to have consecutive equal assertions as long as you don't change the state of the subject (without using Ember.run).

Testing Stores in Flux Architecture

So I am using Reflux for my stores and actions. I have an application store that some application wide data including a flag on whether or not prevent double click is enabled. my tests look like this (using mocha, chai, and sinon):
var applicationStore = require('../../../../web/app/components/core/application.store.js');
var initialState = _.clone(applicationStore._internalData, true);
function resetToInitialState() {
applicationStore._internalData = _.clone(initialState, true);
}
chai.use(sinonChai);
describe('application store', function() {
beforeEach(function() {
resetToInitialState();
});
it('should have default data set properly', function() {
expect(applicationStore.getPreventDoubleClick()).to.be.false;
});
it('should be able to enable prevent double click flag', function() {
applicationStore._onEnablePreventDoubleClick();
expect(applicationStore.getPreventDoubleClick()).to.be.true;
});
it('should be able to disable prevent double click flag', function() {
applicationStore._onEnablePreventDoubleClick();
applicationStore._onDisablePreventDoubleClick();
expect(applicationStore.getPreventDoubleClick()).to.be.false;
});
});
Since the all stores are effectively singletons, is manually reseting it's internal data in the beforeEach a valid way to test to make sure no test effects another one? Is there a better way of doing this with mocha/chai/sinon?
Since I use JestJS I haven't ran into that issue. It seems to deal with singletons really well.
I'm assuming, recommending to switch testing frameworks is out of the question.
If that is the case, then your set up seems ok. My other thought would be to have it inline with the store.
var _internalData = false;
var applicationStore = {
reset: function() {
_internalData = false;
}
};
Then you could just call applicationStore.reset() to reset it, and test the reset functionality.
Neither ideal really.

How do you spy on AngularJS's $timeout with Jasmine?

I am trying to spy on $timeout so that I can verify that it has not been called. Specifically, my production code (see below) calls $timeout as a function, not an object:
$timeout(function() { ... })
and not
$timeout.cancel() // for instance
Jasmine, however, requires an object to be spied upon, like this:
spyOn(someObject, '$timeout')
I don't know what 'someObject' would be though.
I am using Angular mocks, if that makes any difference.
Edit: The relevant production code I'm trying to test looks like this:
EventHandler.prototype._updateDurationInOneSecondOn = function (call) {
var _this = this;
var _updateDurationPromise = this._$timeout(function () {
call.duration = new Date().getTime() - call.startTime;
_this._updateDurationInOneSecondOn(call);
}, 1000);
// ... more irrelevant code
}
In the specific test scenario I am trying to assert that $timeout was never called.
Edit 2: Specified clearly that I am using $timeout as a function, not an object.
Ran into the same problem and ended up decorating the $timeout service with a spy.
beforeEach(module(function($provide) {
$provide.decorator('$timeout', function($delegate) {
return sinon.spy($delegate);
});
}));
Wrote more about why this works here.
In angular $timeout is a service that executes/calls a function. The request to "spy" $timeout is a bit odd being the case that what it is doing is executing X function in Y given time. What I would do to spy this services is to "mock" the timeout function and inject it in your controller something like:
it('shouldvalidate time',inject(function($window, $timeout){
function timeout(fn, delay, invokeApply) {
console.log('spy timeout invocation here');
$window.setTimeout(fn,delay);
}
//instead of injecting $timeout in the controller you can inject the mock version timeout
createController(timeout);
// inside your controller|service|directive everything stays the same
/* $timeout(function(){
console.log('hello world');
x = true;
},100); */
var x = false; //some variable or action to wait for
waitsFor(function(){
return x;
},"timeout",200);
...
This code works for me
var element, scope, rootScope, mock = {
timeout : function(callback, lapse){
setTimeout(callback, lapse);
}
};
beforeEach(module(function($provide) {
$provide.decorator('$timeout', function($delegate) {
return function(callback, lapse){
mock.timeout(callback, lapse);
return $delegate.apply(this, arguments);
};
});
}));
describe("when showing alert message", function(){
it("should be able to show message", function(){
rootScope.modalHtml = undefined;
spyOn(mock, 'timeout').and.callFake(function(callback){
callback();
});
rootScope.showMessage('SAMPLE');
expect(rootScope.modalHtml).toBe('SAMPLE');
});
});

How to mock an function of an Angular service in Jasmine

I have the following angular controller
function IndexCtrl($scope, $http, $cookies) {
//get list of resources
$http.get(wtm.apiServer + '/v1/developers/me?access_token=' + $cookies['wtmdevsid']).
success(function(data, status, headers, config) {
// snip
}).
error(function(data, status, headers, config) {
// snip
});
$scope.modal = function() {
// snip
}
return;
}
What I am trying to do is mock the get method on the $http service. Here's my unit test code:
describe('A first test suite', function(){
it("A trivial test", function() {
expect(true).toBe(true);
});
});
describe('Apps', function(){
describe('IndexCtrl', function(){
var scope, ctrl, $httpBackend;
var scope, http, cookies = {wtmdevsid:0};
beforeEach(inject(function($injector, $rootScope, $controller, $http) {
scope = $rootScope.$new();
ctrl = new $controller('IndexCtrl', {$scope: scope, $http: $http, $cookies: cookies});
spyOn($http, 'get');
spyOn(scope, 'modal');
}));
it('should create IndexCtrl', function() {
var quux = scope.modal();
expect(scope.modal).toHaveBeenCalled();
expect($http.get).toHaveBeenCalled();
});
});
});
When I run this I get
ReferenceError: wtm is not defined.
wtm is a global object and of course it wouldn't be defined when I run my test because the code that it is declared in is not run when I run my test. What I want to know is why the real $http.get function is being called and how do I set up a spy or a stub so that I don't actually call the real function?
(inb4 hating on globals: one of my coworkers has been tasked with factoring those out of our code :) )
You need to wire up the whenGET method of your $httpBackend in advance of your test. Try setting it up in the beforeEach() function of your test... There is a good example here under "Unit Testing with Mock Backend".
I suggest all globals used the way you described here should be used through the $window service.
All global variables that are available, such as as window.wtm, will also be available on $window.atm.
Then you can stub out your wtm reference completely and spy on it the same way you already described:
var element, $window, $rootScope, $compile;
beforeEach(function() {
module('fooApp', function($provide) {
$provide.decorator('$window', function($delegate) {
$delegate.wtm = jasmine.createSpy();
return $delegate;
});
});
inject(function(_$rootScope_, _$compile_, _$window_) {
$window = _$window_;
$rootScope = _$rootScope_;
$compile = _$compile_;
});
});
Maybe you could create a custom wrapper mock around $httpBackend that handles your special needs.
In detail, Angular overwrites components of the same name with a last-come first-served strategy, this means that the order you load your modules is important in your tests.
When you define another service with the same name and load it after the first one, the last one will be injected instead of the first one. E.g.:
apptasticMock.service("socket", function($rootScope){
this.events = {};
// Receive Events
this.on = function(eventName, callback){
if(!this.events[eventName]) this.events[eventName] = [];
this.events[eventName].push(callback);
}
// Send Events
this.emit = function(eventName, data, emitCallback){
if(this.events[eventName]){
angular.forEach(this.events[eventName], function(callback){
$rootScope.$apply(function() {
callback(data);
});
});
};
if(emitCallback) emitCallback();
}
});
This service offers the exact same interface and behaves exactly like the original one except it never communicates via any socket. This is the service we want to use for testing.
With the load sequence of angular in mind, the tests then look like this:
describe("Socket Service", function(){
var socket;
beforeEach(function(){
module('apptastic');
module('apptasticMock');
inject(function($injector) {
socket = $injector.get('socket');
});
});
it("emits and receives messages", function(){
var testReceived = false;
socket.on("test", function(data){
testReceived = true;
});
socket.emit("test", { info: "test" });
expect(testReceived).toBe(true);
});
});
The important thing here is that module('apptasticMock') gets executed after module('apptastic'). This overwrites the original socket implementation with the mocked one. The rest is just the normal dependency injection procedure.
This article I wrote could be interesting for you, as it goes into further details.