I'm developing some unitTests using Jasmine. I'm currently working on Windows8.1 and when I run my test I get following error message.
TypeError: jasmine.getFixtures() is not a function
This is the code that I'm using. I don't know what I must change in order to do this work.
Karma.conf.js
//More configuration entries
...........
files: [
// app-specific code
'src/app/app.js',
// 3rd-party resources
'node_modules/angular-mocks/angular-mocks.js',
// test files
'test/unit/**/*.js',
//fixture to serve mockData in Tests
{ pattern: 'test/unit/mock-data/*.json' }
]
Here is the piece of code from my test.
it('Should load my fixture', function(){
jasmine.getFixtures().fixturesPath = 'HpIpsUi/test/unit/mock-data';
var json = readFixtures('diagnostics.json');
var result = JSON.parse(json);
expect(result).toBeDefined();1
})
It's not recognizing my call to the function jasmine.getFictures().
Thank you for your help
Have you included the jasmine-query library? It's defined there, not in the jasmine library.
Said jasmine-query.js needs to be downloaded, and added as file, because it's not installable with npm yet.
Related
I'm trying to get a basic unit test example working. It all works fine with this app.js
var whapp = angular.module('whapp', [])
.filter('reverse',[function(){
return function(string){
return string.split('').reverse().join('');
}
}]);
and this spec.js
describe('Filters', function(){ //describe your object type
beforeEach(module('whapp')); //load module
describe('reverse',function(){ //describe your app name
var reverse, rootScope;
beforeEach(inject(function($filter){ //initialize your filter
reverse = $filter('reverse',{});
}));
it('Should reverse a string', function(){ //write tests
expect(reverse('rahil')).toBe('lihar'); //pass
});
});
});
with this karma files config
files: [
'node_modules/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'node_modules/angular-mocks/angular-route/angular-route.js',
'node_modules/angular-mocks/angular-ui-router/release/angular-ui-router.js',
'app/js/*.js',
'tests/*.js'
]
The problem occurs when I try to inject ngRoute into my module in app.js like so
var whapp = angular.module('whapp', ['ngRoute'])
.filter('reverse',[function(){
return function(string){
return string.split('').reverse().join('');
}
}]);
In which case I get the following error in karma [UPDATE: this error occurs even if I don't load the angular-mock.js library into karma as shown above]
TypeError: undefined is not a constructor (evaluating 'reverse('rahil')') in tests/spec.js (line 9)
So... how do I inject ngRoute into spec.js correctly? I've tried a variety of things, none of which worked.
Apparently, you get this error because PhantomJS fails to instantiate your main Angular module whapp. One possible reason is, that the file node_modules/angular-mocks/angular-route/angular-route.js is missing.
Obviously, you are using npm to manage your dependencies. So try to replace your current file with:
node_modules/angular-route/angular-route.js
The same for the ui-route module:
node_modules/angular-ui-router/release/angular-ui-router.js
I hope this will help you.
I'm using the expect.js library with my mocha unit tests. Currently, I'm requiring the library on the first line of each file, like this:
var expect = require('expect.js');
describe('something', function () {
it('should pass', function () {
expect(true).to.be(true); // works
});
});
If possible, I'd like to remove the boilerplate require code from the first line of each file, and have my unit tests magically know about expect. I thought I might be able to do this using the mocha.opts file:
--require ./node_modules/expect.js/index.js
But now I get the following error when running my test:
ReferenceError: expect is not defined
This seems to make sense - how can it know that the reference to expect in my tests refers to what is exported by the expect.js library?
The expect library is definitely getting loaded, as if I change the path to something non-existent then mocha says:
"Error: Cannot find module './does-not-exist.js'"
Is there any way to accomplish what I want? I'm running my tests from a gulp task if perhaps that could help.
You are requiring the module properly but as you figured out, the symbols that the module export won't automatically find themselves into the global space. You can remedy this with your own helper module.
Create test/helper.js:
var expect = require("expect.js")
global.expect = expect;
and set your test/mocha.opts to:
--require test/helper
While Louis's answer is spot on, in the end I solved this with a different approach by using karma and the karma-chai plugin:
Install:
npm install karma-chai --save-dev
Configure:
karma.set({
frameworks: ['mocha', 'chai']
// ...
});
Use:
describe('something', function () {
it('should pass', function () {
expect(true).to.be(true); // works
});
});
Thanks to Louis answer and a bit of fiddling around I sorted out my test environment references using mocha.opts. Here is the complete setup.
My project is a legacy JavaScript application with a lot of "plain" js files which I wish to reference both in an html file using script tags and using require for unit testing with mocha.
I am not certain that this is good practice but I am used to Mocha for unit testing in node project and was eager to use the same tool with minimal adaptation.
I found that exporting is easy:
class Foo{...}
class Bar{...}
if (typeof module !== 'undefined') module.exports = { Foo, Bar };
or
class Buzz{...}
if (typeof module !== 'undefined') module.exports = Buzz;
However, trying to use require in all the files was an issue as the browser would complain about variables being already declared even when enclosed in an if block such as:
if (typeof require !== 'undefined') {
var {Foo,Bar} = require('./foobar.js');
}
So I got rid of the require part in the files and set up a mocha.opts file in my test folder with this content. The paths are relative to the root folder:
--require test/mocha.opts.js
mocha.opts.js content. The paths are relative to the location of the file:
global.assert = require('assert');
global.Foo = require("../foobar.js").Foo;
global.Bar = require("../foobar.js").Bar;
global.Buzz = require("../buzz.js");
I am trying to set up unit testing for a SPA using karma/jasmine
First of all, the following test runs just fine in karma:
/// <reference path="../../definitions/jasmine/jasmine.d.ts" />
/// <reference path="../../src/app/domain/core/Collections.ts"/>
define(["app/domain/core/Collections"], (collections) => {
describe('LinkedList', () => {
it('should be able to store strings for lookup', () => {
var list = new collections.Collections.LinkedList<string>();
list.add("item1");
expect(list.first()).toBe("item1");
});
});
});
However, collections is of type anyso that I can not use it for type declarations, thus I'm missing intellisense and whatnot when I am writing my tests. No good!
The problem arises when I try to re-write the test to a more TypeScript friendly format:
/// <reference path="../../definitions/jasmine/jasmine.d.ts" />
/// <reference path="../../src/app/domain/core/Collections.ts"/>
import c = require("./../../src/app/domain/core/Collections");
describe('LinkedList', () => {
it('should be able to store strings for lookup', () => {
var list: c.Collections.LinkedList<string> = new c.Collections.LinkedList<string>();
list.add("item1");
expect(list.first()).toBe("item1");
});
});
This compiles just fine, I get my type information for handy intellisense etc, but now karma throws an error.
It turns out it is trying to load the module without the .js postfix, indicated by the following error messages:
There is no timestamp for /base/src/app/domain/core/Collections!
Failed to load resource: the server responded with a status of 404 (Not Found)
(http://localhost:9876/base/src/app/domain/core/Collections)
Uncaught Error: Script error for: /base/src/app/domain/core/Collections
I'm gonna stop here for now, but if it will help I am glad to supply my karma config file, test-main and so on. But my hope is that someone has encountered this exact problem before and might be able to point me in the right direction.
My typescript is compiled with the AMD flag.
It is not a TypeScript problem. We encountered the same problem. Turns out that karma "window.__karma__.files" array includes all files included in the test, including the .js extenstion.
Now requireJS does not work when supplying the .js extension. To fix it, in our main-test.js file, we created a variable "tests" by filtering all the *Spec.js files and then we removed the .js from the file name as requireJS needs it to be. More information here: http://karma-runner.github.io/0.8/plus/RequireJS.html
Below is how we did it (based on the info supplied in the link above):
main-test.js
console.log('===========================================')
console.log('=================TEST FILES================')
var tests = Object.keys(window.__karma__.files).filter(function (file) {
return /\Spec\.js$/.test(file);
}).map(function (file) {
console.log(file);
return file.replace(/^\/base\/|\.js$/g, '');
});
console.log('===========================================')
console.log('===========================================')
require.config({
baseUrl:'/base',
paths: {
jquery :["http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min", "lib/jquery"],
angular : ["https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.14/angular.min", "lib/angular"],
angularMocks: 'app/vendors/bower_components/angular-mocks/angular-mocks',
},
shim: {
'angularMocks': {
deps: ['angular'],
exports: 'angular.mock'
}
},
deps: tests,
callback: window.__karma__.start
});
Also make sure you have supplied the files to be tested in your karma.config.js file, more details here: http://karma-runner.github.io/0.8/plus/RequireJS.html same as the link above.
Hope it helps
It turns out it is trying to load the module without the .js postfix,
That is the perhaps not the actual source of the error. Actually it is looking at /base/src/app/domain/core/Collections and not app/domain/core/Collections (as in your manual type unsafe way). Notice base/src/ that shouldn't be there.
I am trying to create and run intern test cases for our non AMD javascript, but have not been able to test it.
I have a javascript file called as DBoard.js which has initial lines as
DBoard.js
dojo.provide("search.DBoard");
dojo.require("search.SContainer");
....
...
I want to test the above file for which I have written the intern test case as
define([
"intern!tdd",
"intern/chai!assert"
],
function (tdd, assert) {
with(assert) {
tdd.suite("test search.DBoard", function() {
tdd.test("test search.DBoard", function() {
var dboard = new search.DBoard();
// assert statements
});
});
}
});
The error which it gives me everytime is that its not able to find search.Dboard.
I dont know how and where we can provide this dependency. I tried using intern!order but even that did not seem to work.
Can anyone please help me in writing this piece of code for testing non AMD code?
In order to load legacy Dojo modules, if you are using Dojo 1.6- you will need to load [ 'intern/order!path/to/dojo.js', 'intern/order!path/to/DBoard.js' ] as dependencies. If you are using Dojo 1.7+ you will need to set useLoader: { 'host-browser': 'path/to/dojo.js' } and then load [ 'path/to/DBoard' ] as a dependency. More information about useLoader can be found in the documentation on using alternative loaders.
As indicated in this stackoverflow answer, it looks like Karma will serve JSON fixtures. However, I've spent too many hours trying to get it to work in my environment. Reason: I'm doing angular testing and need to load mock HTTP results into the test, as Jasmine doesn't support any global setup/teardown with mock servers and stuff.
In my karma config file, I'm defining a fixture as so:
files: [
// angular
'angular/angular.min.js',
'angular/angular-route.js',
'angular/mock/angular-mocks.js',
// jasmine jquery helper
'jquery-1.10.2.min.js',
'angular/jasmine-jquery.js',
// our app
'../public/js/FooApp.js',
// our tests
'angular/*-spec.js',
// fixtures
{ pattern: 'node/mock/factoryResults.json',
watched: 'true',
served: 'true',
included: 'false' }
]
Before I even attempt to use jasmine-jquery.js in my jasmine test to load the JSON, I see karma choking on trying to serve it:
...
DEBUG [web-server]: serving: /Users/XXX/FooApp/spec/node/mock/factoryResults.json
Firefox 25.0.0 (Mac OS X 10.8) ERROR
SyntaxError: missing ; before statement
at /Users/XXX/FooApp/spec/node/mock/factoryResults.json:1
...
Here's what factoryResults.json looks like:
{ "why": "WHY" }
Any idea what's going on here? I see plenty of examples on the web of folks successfully loading JSON into jasmine tests via karma fixtures. Karma can see the file; if I put the wrong path in my fixture block, I see an error stating that it couldn't find any files that match my fixture pattern. I've tried reformatting the .json file in different ways... Any ideas?
Your problem is that 'false' has to be a boolean, not a string.
There is already an issue to validate the config better and fix such a mistakes.
Also, you might write a simple "json" preprocessor (similar to karma-html2js) that would make it valid JS and put the JSON into some global namespace so that you can keep the tests synchronous...
I also needed json fixtures in my karma test suite.
I ended up just using the html2js preprocessor with json files as well as html.
karma.conf.js:
module.exports = function (config) {
config.set({
frameworks: ["jasmine"],
files: [
'**/*.js',
'**/*.html',
'**/*.json',
'**/*.spec.js'
],
plugins: [
'karma-html2js-preprocessor'
]
preprocessors: {
'**/*.html': ['html2js'],
'**/*.json': ['html2js']
}
});
};
Then it is just a matter of getting the json from the __html__ global.
e.g.
var exampleJson = __html__['example.json'];
var jsonObj = JSON.parse(exampleJson);
var exampleHtml = __html__['example.html'];
document.body.innerHTML = exampleHtml;
So, I had a lot of issues with jasmine-jquery and I got a pretty decent workaround.
It's a little hacky, but it works. Basically, I just create a function accessible on the window, then stack the JSON fixtures inside a little switch:
if (typeof(window.fixtures === "undefined")) {
window.fixtures = {};
}
window.setFixture = function(type) {
var json;
if (type == "catalog") {
json = { ... }
}
if (typeof(type) !== "undefined") {
window.fixtures[type] = json;
}
return json;
}
Then, I can just stub it inline in the view:
describe "App.Models.Catalog", ->
it "provides the 'App.Models.Catalog' function", ->
expect(App.Models.Catalog).toEqual(jasmine.any(Function))
it "sets up a fixture", ->
setFixture("catalog")
console.log(fixtures["catalog"])
expect(fixtures["catalog"]).toBeDefined()
Boom, tests pass, and the object comes out in the log:
{
catalog_id: '2212',
merchant_id: '114',
legacy_catalog_id: '2340',
name: 'Sample Catalog',
status: '1',
description: 'Catalog Description ',
}
Now, it's accessible within my test.
It's of course not perfect or ideal, but I kept hitting strange matchErrors and the like with the jasmine-jquery plugin, and it's simple enough (and fast) for me to paste in a couple of JSON blocks and get moving.
You also save yourself the time fiddling around with the configuration and making any changes to the files for Karma.
Anyone have any better suggestions or have any luck getting jasmine-jquery to work?