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.
Related
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.
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();
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)
I have a simple mocha test that fails when using requirejs and the context config.
Here's A.js
define([], function(){
return {};
});
Here's the test spec.js
var requirejs = require('requirejs');
var localReq = requirejs.config({
baseUrl: "./",
context: "context1"
})
describe("context test", function () {
it("should not throw error", function () {
for (var i = 0; i < 100; i++) {
console.log(localReq("A"), i);
}
});
});
When I run the test mocha spec.js, I get the following error:
Uncaught Error: Tried loading "A" at /Users/khirakawa/work/test/node_modules/mocha/bin/A.js then tried node's require("A") and it failed with error: Error: Cannot find module 'A'
Here's a screenshot:
Notice how A was properly loaded and logged 100 times, yet the test still failed. If I comment out the context config, it works just fine.
Mocha is also printing out '1 passing' and '1 failing', even though there is only 1 test.
Why is this happening?
You could write your test like this:
describe("context test", function () {
it("should not throw error", function (done) {
localReq(["A"], function (f) { done(); });
});
});
As you pointed out in a comment, calling localReq to get a module synchronously should work but for some unexplained reason it does not. The code above, which calls localReq to load the module asynchronously, works.
The reason Mocha is saying that your single test is passing and failing is that it is detecting an error that happens after your test is over and has no other test to associate it with. This kind of error message where the same test both passes and fails is a sure indication that you've got something happening asynchronously but that you have not taken care of it in your Mocha test setup.
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.