Get the function arguments for unit testing in NativeScript - unit-testing

i'm kinda new to JS and NS but i'm trying to do some unit test with an nativescript app and my onTap function doesn't "start" when called. I think it may come from the arguments of my onTap but i tried to export it and it didn't work. Thanks for helping. (I'm using Jasmine)
My function looks like this :
function onTap(args) {
let a = 10;
exports.a = a;
}
exports.onTap = onTap;
And my test :
var varTest = require('../home/home-page.js');
describe("test_onTap", function() {
beforeAll(function() {
varTest.onTap(arguments);
});
it("should return true", function() {
expect(varTest.a).toEqual(10);
});
});

Related

knockout - unit testing computed observables

In knockout, i want to unit test the value of a computed observable that depends on another observable, using jasmine.
However, it doesn't work, as the value of the computed observable doesn't update when i change the other observable.
Here is my (simplified) view model:
function MarkersViewModel() {
var self = this;
self.name = ko.observable("chad");
self.computedName = ko.computed(function() {
return self.name();
});
Here is my jasmine spec:
describe("string", function() {
var view_model = new MarkersViewModel();
view_model.name = ko.observable("joe");
it("returns the whole array when there is no filter", function() {
expect(view_model.computedName()).toBe("joe");
});
});
When i run this, jasmine fails:
Expected 'chad' to be 'joe'.
Any idea on how i could implement that?
Thanks
You should not recreate observable, just set value:
describe("string", function() {
var view_model = new MarkersViewModel();
view_model.name("joe"); // <- here
it("returns the whole array when there is no filter", function() {
expect(view_model.computedName()).toBe("joe");
});
});
Your computed scoped original observable (with "chad" assigned in constructor function) and used it.
It may be useful to the same solution solution with QUnit :
test(" Test view_model.name ", function () {
var view_model = new MarkersViewModel();
view_model.name("joe");
equal(view_model.computedName(), "joe");
});
https://github.com/thedom85/Javascript_Knockout_QUnit_Example

How do I unit test a helper that uses a service?

I'm trying to unit test a helper that uses a service.
This is how I inject the service:
export function initialize(container, application) {
application.inject('view', 'foobarService', 'service:foobar');
}
The helper:
export function someHelper(input) {
return this.foobarService.doSomeProcessing(input);
}
export default Ember.Handlebars.makeBoundHelper(someHelper);
Everything works until here.
The unit test doesn't know about the service and fails. I tried to:
test('it works', function(assert) {
var mockView = {
foobarService: {
doSomeProcessing: function(data) {
return "mock result";
}
}
};
// didn't work
var result = someHelper.call(mockView, 42);
assert.ok(result);
});
The error:
Died on test #1 at http://localhost:4200/assets/dummy.js:498:9
at requireModule (http://localhost:4200/assets/vendor.js:79:29)
TypeError: undefined is not a function
Everything is correct, the only change needed was:
var result = someHelper.call(mockView, "42");

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

Testing asynchrone function gives Unexpected request

The unittest:
"use strict";
var usersJSON = {};
describe("mainT", function () {
var ctrl, scope, httpBackend, locationMock,
beforeEach(module("testK"));
beforeEach(inject(function ($controller, $rootScope, $httpBackend, $location, $injector) {
scope = $rootScope.$new();
httpBackend = $httpBackend;
locationMock = $location;
var lUrl = "../solr/users/select?indent=true&wt=json",
lRequestHandler = httpBackend.expect("GET", lUrl);
lRequestHandler.respond(200, usersJSON);
ctrl = $controller("mainT.controller.users", { $scope: scope, $location: locationMock});
httpBackend.flush();
expect(scope.users).toBeDefined();
}));
afterEach(function () {
httpBackend.verifyNoOutstandingRequest();
httpBackend.verifyNoOutstandingExpectation();
});
describe("method test", function () {
it('should test', function () {
expect(true).toBeFalsy();
});
});
});
controller I'm testing (working):
Asynchrone function in init who's giving me trouble (uses ../solr/users/select?indent=true&wt=json):
$scope.search = function () {
var lStart = 0,
lLimit = privates.page * privates.limit;
Search.get({
collection: "users",
start: lStart,
rows: lLimit)
}, function(records){
$scope.users= records.response.docs;
});
};
What I think happens:
1. inform backend what request he will receive
2. inform backend to response on that request with empty JSON
3. create a controller (Search.get get's executed)
4. inform backend to receive all requests and answer them (flush)
Yet I always get the following error:
Error: Unexpected request: GET : ../solr/users/select?indent=true&wt=json
Am I not handling the asynchrone search function well? how should this be done?
That's not really a "unit" test, it's more of a behavioral test.
This should really be a few tests:
Test your service Search.get to make sure it's calling the proper URL and returning the result.
Test your controller method to make sure it's calling Search.get
Test your controller method to make sure it's putting the result in the proper spot.
The code you've posted is a little incomplete, but here are two unit tests that should cover you:
This is something I've blogged about extensively, and the entries go into more detail:
Unit Testing Angular Controllers
Unit Testing Angular Services
Here's an example of what I'm talking about:
describe('Search', function () {
var Search,
$httpBackend;
beforeEach(function () {
module('myModule');
inject(function (_Search_, _$httpBackend_) {
Search = _Search_;
$httpBackend = _$httpBackend_;
});
});
describe('get()', function () {
var mockResult;
it('should call the proper url and return a promise with the data.', function () {
mockResult = { foo: 'bar' };
$httpBackend.expectGET('http://sample.com/url/here').respond(mockResult);
var resultOut,
handler = jasmine.createSpy('result handler');
Search.get({ arg1: 'wee' }).then(handler);
$httpBackend.flush();
expect(handler).toHaveBeenCalledWith(mockResult);
$httpBackend.verifyNoOutstandingRequest();
$httpBackend.verifyNoOutstandingExpectation();
});
});
});
describe('myCtrl', function () {
var myCtrl,
$scope,
Search;
beforeEach(function () {
module('myModule');
inject(function ($rootScope, $controller, _Search_) {
$scope = $rootScope.$new();
Search = _Search;
myCtrl = $controller('MyCtrl', {
$scope: scope
});
});
});
describe('$scope.foo()', function () {
var mockResult = { foo: 'bar' };
beforeEach(function () {
//set up a spy.
spyOn(Search, 'get').andReturn({
then: function (fn) {
// this is going to execute your handler and do whatever
// you've programmed it to do.. like $scope.results = data; or
// something.
fn(mockResult);
}
});
$scope.foo();
});
it('should call Search.get().', function () {
expect(Search.get).toHaveBeenCalled();
});
it('should set $scope.results with the results returned from Search.get', function () {
expect(Search.results).toBe(mockResult);
});
});
});
In a BeforeEach you should use httpBackend.when instead of httpBackend.expect. I don't think you should have an assertion (expect) in your BeforeEach, so that should be moved to a separate it() block. I also don't see where lRequestHandler is defined. The 200 status is sent by default so that is not needed. Your httpBackend line should look like this:
httpBackend.when("GET", "/solr/users/select?indent=true&wt=json").respond({});
Your test should then be:
describe("method test", function () {
it('scope.user should be defined: ', function () {
expect(scope.user).toEqual({});
});
});
Your lUrl in the unit test, shouldn't be a relative path, i.e., instead of "../solr/users/select?indent=true&wt=json" it should be an absolute "/solr/users/select?indent=true&wt=json". So if your application is running at "http://localhost/a/b/index.html", lUrl should be "/a/solr/...".
Note that you can also use regular expressions in $httpBackend.expectGET(), that could be helpful here in case you are not entirely sure how the absolute path will look like later on.

How to write unit test for AngularJS model

I've got a basic model that I am trying to write a simple unit test suite for, and I'm clearly missing something...
The code for the model looks like this:
angular.module('AboutModel', [])
.factory(
'AboutModel',
[
function () {
var paragraphs = [];
var AboutModel = {
setParagraphs: function (newParagraphs) {
paragraphs = newParagraphs;
},
getParagraphs: function () {
return paragraphs;
}
};
return AboutModel;
}
]
);
The requirement is simple: provide a getter and a setter method for the private array called paragraphs.
And here is as far as I have got with the test suite code:
describe('Testing AboutModel:', function () {
describe('paragraphs setter', function () {
beforeEach(module('AboutModel'));
it('sets correct value', inject(function (model) {
// STUCK HERE
// don't know how to access the model, or the setParagraphs() method
}));
});
describe('paragraphs getter', function () {
// not implemented yet
});
});
I've been doing quite a bit of google research on the web, but so far no joy.
The solution must be simple; please help!
And it might even be the case that there's a better way of implementing the Model... open to suggestions to make it better.
For anyone interested, the full source code is here:
https://github.com/mcalthrop/profiles/tree/imp/angular
thanks in advance
Matt
You need to run a beforeEach in your test to inject the model instance and then assign it to a variable which you can then re-use through out your tests.
var AboutModel;
beforeEach(inject(function (_AboutModel_) {
AboutModel = _AboutModel_;
}));
You can then access your getter like so:
AboutModel.getParagraphs();
I have tweaked your original model slightly as I feel it reads a little better (my preference):
'use strict';
angular.module('anExampleApp')
.factory('AboutModel', function () {
var _paragraphs;
// Public API here
return {
setParagraphs: function (newParagraphs) {
_paragraphs = newParagraphs;
},
getParagraphs: function () {
return _paragraphs;
}
};
});
And then for testing I would use a combination of the standard Jasmine tests and spies:
'use strict';
describe('Service: AboutModel', function () {
beforeEach(module('anExampleApp'));
var AboutModel, paragraphs = ['foo', 'bar'];
beforeEach(inject(function (_AboutModel_) {
AboutModel = _AboutModel_;
}));
it('should set new paragraphs array', function () {
AboutModel.setParagraphs([]);
expect(AboutModel.getParagraphs()).toBeDefined();
});
it('should call setter for paragraphs', function () {
spyOn(AboutModel, 'setParagraphs');
AboutModel.setParagraphs(paragraphs);
expect(AboutModel.setParagraphs).toHaveBeenCalledWith(paragraphs);
});
it('should get 2 new paragraphs', function () {
AboutModel.setParagraphs(['foo', 'bar']);
expect(AboutModel.getParagraphs().length).toEqual(2);
});
});