JavaScript unit tests with Jasmine and RequireJS - javascript

In my visual studio I have two projects one of them provide functionality for SharePoint page and another one for testing purposes.
In the first project I have few view modules that use RequireJS as a dependency injector.
I need to write js tests in another project:
/// <reference path="Scripts/require.js" />
describe('directly', function () {
beforeEach(function() {
require.config({
baseUrl: '../CopmanyName/Layouts/1033/Scripts/CopmanyName/ProjectName/app',
});
});
it('should see booking', function (done) {
require(['Booking'],
function (booking) {
expect(booking).toBeDefined();
done();
});
});
});
The test failed. It appears that requireJS is not able find the Booking module, which is defined like that:
define(['knockout','moment'], function(ko, moment) {
return function Booking(data) {// some functionality}
The error message is: "Expected undefined to be defined." in expect(booking).toBeDefined();

Related

Unknown proider error with karma jasmine unit tests

I have a unit test that is created with the Jasmine framework. When I put a single test specification in the describe block I get a pass in the karma console. If I copy that describe block with the test in it ( the it(); ) then I suddenly start getting problems with dependencies that the module uses.
In the console I get errors around unknown providers.
Here is my simple test:
describe('service definition tests', function () {
it('should be defined', function () {
expect(sut).toBeDefined();
});
});
and that passes okay. If I copy this block I get an error about dependencies. Which is strange as I've already proved that I can test the 'sut' is defined in the first test.
One thing to note is that I have a beforeEach block that loads the module and provides a dependency and it is this dependency that errors when I've duplicated the test. Here is the beforeEach:
var mockConfig = {};
beforeEach(function () {
module('app');
module(function ($provide) {
$provide.value('myConfig', mockConfig);
});
});
the problem has to be something to do with this beforeEach being as the error I get is about the myConfig dependency.
Here is the error:
uncaught Error: [$injecor:unpr] Unknown provider: myConfigProvider <- myConfig <- authorisation
http://errors.angularjs.org/1.4.6/$injector/unpr?p0=myConfiProvider
I managed to resolve this issue by creating a dummy implementation of myConfig factory so that the test files used this.
angular.module('app').factory('myConfig', function() {
var env = 'test';
return {
env: env
}
});
This code lives in a js file that is loaded with the rest of the tests.

AngularJS Test a Factory with Mocha

I am new to Mocha and AngularJS Unit Testing but want to test my application using Mocha. I have basic language tests working, but I cannot run tests against my applications Factory or Controller.
I have the following basic files.
apps.js
aangular.module('MyApp', []);
file1.js
angular.module('MyApp').factory('Factory1' ...);
file2.js
angular.module('MyApp').factory('Factory2' ...);
angular.module('MyApp').factory('Controller' ...);
describe('Main Test', function() {
var FactoryToTest;
beforeEach(module('MyApp'));
beforeEach(inject(function (_Factory_) {
FactoryToTest = _Factory_;
}));
describe('Factory2', function () {
it('should return "unknown"', function () {
Game = {};
expect(new Factory2(Game)).to.equal('unknown');
});
});
});
When I run the test, it generates an error, and I am not sure what to fix to get this to work.
Error:
Message:
object is not a function
Stack:
TypeError: object is not a function
at Suite.<anonymous> (b:\app\test.js:5:16)
You're getting an error because the beforeEach function should take a callback function instead of an object. According to the Angular guide on module unit testing (scroll to bottom of the page) :
Each module can only be loaded once per injector. Usually an Angular app has only one injector and modules are only loaded once. Each test has its own injector and modules are loaded multiple times.

Loading AngularJS module in Jasmine test via Grunt

I am trying to write some unit tests for an AngularJS service. I want to run the unit tests from the command-line via Grunt. In an attempt to do that, I've written the following:
gruntfile.js
'use strict';
module.exports = function (grunt) {
grunt.initConfig({
jasmine: {
service: {
src: 'dist/myService.js',
options: {
specs: 'test/*.js',
vendor: [
'bower_components/angularjs/angular.min.js',
'bower_components/angular-mocks/angular-mocks.js'
]
}
}
}
});
// load all grunt task details
require('load-grunt-tasks')(grunt);
grunt.registerTask('default', ['jasmine:service']);
};
dist/myService.js
'use strict';
angular.module('myModule')
.factory('$myService', function () {
return {
getResult: function () {
return 3;
}
};
})
;
test/serviceTests.spec.js
describe('myModule', function() {
beforeEach(function() {
console.log('loading module...');
module('myModule');
});
describe('$myService', function () {
it('should work', function () {
console.log('testing');
expect(1 + 2).toEqual(3);
});
});
})
When I try to run this, I get the following error:
Running "jasmine:service" (jasmine) task
Testing jasmine specs via PhantomJS
>> Error: [$injector:nomod] http://errors.angularjs.org/1.2.22/$injector/nomod?p0=myModule at
>> ..\..\..\C:\source\myModule\bower_components\angularjs\angular.min.js:20
>> ..\..\..\C:\source\myModule\bower_components\angularjs\angular.min.js:21
>> ..\..\..\C:\source\myModule\dist\myService.js
myModule
$myService
- should work...
log: loading module...
log: testing
√ should work
I know that in order to test my service, I need to inject it. However, at this time, I'm getting an error loading the module itself. For that reason, I know that I cannot inject my service. However, I do not know why the module won't load. I've confirmed that I have the correct src value.
Can anybody tell me what I'm doing wrong? Or, perhaps point me to the smallest possible example of testing a service in AngularJS (complete with Grunt, etc.)?
I just don't understand what is wrong with my approach. Thank you for your help.
When you call angular.module('myModule') (without second parameter) Angular tries to reference already existing module and cannot find it.
To declare a new module you should call angular.module('myModule', []) (with two parameters)

How to de-bootstrap an angular js application in unit tests?

In my jasmine tests I test the app initialization the following way:
(function () {
"use strict";
describe('app', function () {
beforeEach(function() {
module('app');
});
it('should load without errors', function() {
expect(function() {
angular.bootstrap(angular.element('body'), ['app']);
}).not.toThrow();
});
});
}());
My problem is that when I run Karma i often get:
Expected function not to throw an exception , but it threw [ng:btstrpd] App Already Bootstrapped with this Element '<body>'
I think the best solution would be to "un-bootstrap" the application in an afterEach but I could not find any way to do so in the docs.
Any ideas?
You're doing the wrong approach, since you can't "un-bootstrap" angular. Instead don't bootstrap it in the first place, when it's not needed: Remove the "ng-app" directive from your marup where your jasmine tests are running.

Access "global" mocha.js functions when using require.js

I am including Mocha.js with the excellent use shim for a Require.js-based site.
How do I access the define() and it() BDD functions declared by Mocha when using Require.js?
Here is a basic code example:
test.js:
var mocha = require('use!mocha')
, testFile = require('testFile.js')
mocha.setup('bdd');
mocha.run();
testFile.js:
define(function(require) {
// describe() and it() are not available
describe('Book', function() {
it('should have pages', function() {
});
});
});
I get the error Uncaught ReferenceError: describe is not defined when running in the browser.
I have tried window.describe and tried moving the require('testFile.js') to after the mocha.setup('bdd'). I know I am missing something. Probably passing the context to mocha somehow.
The problem is that the global functions such as describe and it are set up by mocha.setup(). You can use shim config's init property to call mocha.setup() before mocha is exported.
requirejs.config({
shim: {
'mocha': {
init: function () {
this.mocha.setup('bdd');
return this.mocha;
}
}
}
});
require(['mocha', 'test/some_test'], function (mocha) {
mocha.run();
});
Test files need to require mocha.
define(['mocha'], function (mocha) {
describe('Something', function () {
// ...
});
});
Shim config's init property was introduced in RequireJS 2.1. You might be able to use exports property instead of init with RequireJS 2.0.
I found the solution in geddski's amd-testing examples project.
Instead of including the test file(s) at the top along with mocha like so:
define(['use!mocha', 'testFile'],
function(Mocha, TestFile) {
mocha.setup('bdd');
mocha.run();
});
The test file(s) should be included as another require call and mocha.run() embedded in the callback:
define(['use!mocha'],
function(Mocha) {
mocha.setup('bdd');
// Include the test files here and call mocha.run() after.
require(['testFile'],
function(TestFile) {
mocha.run();
});
});

Categories