Referencing JavaScript files from Jasmine tests - javascript

I am writing some utilities that I intend to reuse across my JavaScript. This is also a learning exercise on my part. In an attempt to do this, I have the following file:
utilities.js
Object.prototype.AddPrefix = function(prefix) {
return prefix + this;
};
I intend to call this function in JavaScript like this:
var myString = 'agree';
myString = myString.AddPrefix('dis');
Please note, that is a contrived example. I'm just trying to demonstrate calling the function. Either way, I want to test the AddPrefix function. To do that, I'm using Jasmine. I have the following Jasmine file:
utilities.tests.js
'use strict';
describe('utilities', function() {
describe('add prefix', function() {
it('append dis to string', function() {
var v = 'agree';
var actual = v.AddPrefix('dis');
var expected = 'disagree';
expect(actual).toBe(expected);
});
});
});
The two files, utilities.js and utilities.tests.js are in the same directory. I am executing Jasmine via gulp with the following script:
gulpfile.js
var gulp = require('gulp');
var jasmine = require('gulp-jasmine');
gulp.task('default', function() {});
gulp.task('test', function() {
var testFiles = [
'utilities/utilities.tests.js'
];
return gulp
.src(testFiles)
.pipe(jasmine());
});
When I execute gulp test from the command-line, I get the following error:
[09:44:33] Using gulpfile C:\Projects\test\gulpfile.js
[09:44:33] Starting 'test'...
F
Failures:
1) utilities add prefix
1.1) TypeError: Object agree has no method 'AddPrefix'
1 spec, 1 failure
Finished in 0 seconds
[09:44:33] 'test' errored after 42 ms
[09:44:33] Error in plugin 'gulp-jasmine'
Message:
Tests failed
Its like utilities.tests.js does not know where utilities.js is located. However, I do not know how to reference it. How do I do this?

Your utilities.js file is never being executed. You need to require('./utilities') in utilities.tests.js:
'use strict';
require('./utilities');
describe('utilities', function() {
describe('add prefix', function() {
it('append dis to string', function() {
var v = 'agree';
var actual = v.AddPrefix('dis');
var expected = 'disagree';
expect(actual).toBe(expected);
});
});
});

Related

JS/Sinon - beforeEach(function(done) not called

Just starting with Sinon, Mocha, and Chai JS. After upgrading UnderscoreJS version from 1.4.4 to 1.9.1, I had to update how my project was using template function.
Previously, _.template function was used in this way -
var myTemplate = _.template("<p><%= name %></p>", {name: 'Joe Doe'});
New Way,
// `myTemplate` here is a function!
var myTemplate = _.template("<p><%= name %></p>");
// Now let's pass in the data for the template.
myTemplate({name: 'Joe Doe'}); // it returns: "<p>Joe Doe</p>"
However, this change caused a lot of the existing test cases to fail. Below mentioned is one of the test cases I need help with -
const sinonVar = require('sinon');
describe('testVar', function() {
var sanboxVar;
var ss = requirejs('Path to JS library');
var testVar;
beforeEach(function(done) {
console.log("Not Called"); // Never printed on console
done();
sanboxVar = sinonVar.sanbox.create();
});
it('some text here', function() {
console.log("sanboxVar: " + sanboxVar); //Printed on console as 'undefined'
ss.id = sanboxVar.stub();
});
});
On "npm test", I see the error -
testVar
some text here:
TypeError: Cannot read property 'stub' of undefined
at Context.<anonymous> (testPage.js) - "This is pointing to sanboxVar not defined"
I think for some reason, beforeEach method is not getting called and hence the Sandoval variable is not getting initiated.
Any help would be appreciated.

Testing Angular Factory with Jasmine is not working

I'm new to Jasmine. I've written a simple code to execute in JS Fiddle which is working perfectly fine. But, when I include jasmine code, its not working. Am I missing anything here?
var app = angular.module('sortModule', [])
app.factory('sortFactory', function(){
var sortedColors = []
var shouldPush = true;
return {
sortColors: function(colorsArray){
var colorsOrder = [{color:'green'},{color:'yellow'},{color:'blue'},{color:'red'}]
for(color in colorsOrder) {
for(objColor in colorsArray) {
shouldPush = colorsOrder[color].color === colorsArray[objColor].color ? true : false
if(shouldPush) {sortedColors.push(colorsArray[objColor]);}
}
}
return sortedColors;
}
}
});
app.controller('sortController', function($scope,sortFactory){
$scope.colorsArray = [{id: '1',color: 'red',code : '#ff0000'},{id: '2',color: 'blue',code : '#0000ff'},{id: '3',color: 'red',code : '#ff0000'},{id: '4',color: 'yellow',code : '#ffff00'},{id: '5',color: 'green',code : '#00ff00'}];
$scope.sortedColors = sortFactory.sortColors($scope.colorsArray)
});
describe('colors', function () {
beforeEach(module('sortModule'));
it('can get the actual sorted ordered colors list', inject(function(sortFactory) {
expect(sortFactory).toBeDefined();
}));
});
var NOT_IMPLEMENTED = undefined;
// load jasmine htmlReporter
(function() {
var env = jasmine.getEnv();
env.addReporter(new jasmine.HtmlReporter());
env.execute();
}());
Actual working fiddle without Jasmine
http://jsfiddle.net/SyedNizamChennai/kjuemhua/15/
New fiddle when Jasmine is included
https://jsfiddle.net/SyedNizamChennai/5d4f0hdL/3/
Test code contains module function
beforeEach(module('sortModule'));
This is function from ngMock module, you need include it as external resource.
https://jsfiddle.net/SyedNizamChennai/5d4f0hdL/3/
EDIT:
working example is here:
http://jsbin.com/lenogujesi/1/edit?html,output
(i used jsbin to better show dependencies and their order)
some notes:
if is jasmine loaded, angular mock expose function mock and others as global (see https://docs.angularjs.org/api/ngMock#function), otherwise function is undefined
angular and angular mock should have same version

Jasmine mocking a constructor within a function

I get an error when running Jasmine tests: 'ReferenceError: JSZip is not defined'. Here's my controller:
$scope.makeZip = function() {
var zip = new JSZip();
zip.file('myPhoto.txt', 'Hello World);
return 'foo' + zip.generate();
};
And test:
it('should make a zip with correct name', function() {
var zipFileName = scope.makeZip();
expect(zipFileName).toMatch('foo');
});
My guess is that I need to mock JSZip constructor somehow: I tried inserting the following at the beginning of the test:
spyOn(window, 'JSZip').andReturn(null);
but then I get 'JSZip() method does not exist'.
I thought this is similar problem to Jasmine - How to spy on a function call within a function?, but I couldn't find a right way to fix the issue.
Any ideas? Thanks for all help!
JSZip is defined on the window. You should not have to pass it into the constructor. In your jasmine page (where you holster your specs), reference jszip.js. If you want, you could create a service..
your angular module.value("JSZip",JSZip);
then pass it into your controller. This is only useful if you wanted to mock JSZip, though.
Solved it! I didn't actually want to test JSZip, only to check whether a function makeZip is called correctly.
it('should make a zip with correct name', function() {
window.JSZip = function() {
this.file = function() {};
this.generate = function() {
return 'bar';
};
};
var zipFileName = scope.makeZip();
expect(zipFileName).toMatch('foo'); //makeZip should return string containing 'foo'
});

How to use mocha test external javascript resources?

I'm trying to run a mocha test to test the function in external js file, but when I try to run mocha test, it gives me nothing, meaning something wrong of my test.js
If I'm test an function internally inside test.js, it works.
this is the reference guide how I generate the below code, http://dailyjs.com/2011/12/08/mocha/
This is the js need to be test (the relative path to test.js is ../../scripts/main)
function add(a,b){
return a+b;
}
module.exports.add = add;
This is my test.js
/* global describe, it */
(function () {
'use strict';
var assert = chai.assert;
var expect = chai.expect;
var should = chai.should();
var add = require('../../scripts/main').add;
describe('test1', function(){
it('should return 3 when add 1 and 2', function(done){
assert.equal(3, add(1,2));
done();
});
});
})();
with #c089 's help, here is the working script :)
/* global describe, it */
(function () {
'use strict';
var add = require('./main').add;
var assert = require("assert");
describe('test1', function(){
it('should return 3 when add 1 and 2', function(done){
assert.equal(5, add(1,2));
done();
});
});
})();

Mocha Global Scoping Issues

I'm having a big problem with my mocha tests around a global object I'm using. I'm able to produce the following MRE which doesn't give the exact same error, but exemplifies the problematic (buggy?) behavior. Any insight would be much appreciated.
I have the following main.js file in /lib:
exports.exec = function(){
console.log(test);
}
Then the following in /test/test.js:
var should = require('should');
var main = require('../lib/main');
global.test = {something: 1};
describe('normal test', function(){
beforeEach(function(){
global.test = {another: 2};
}),
afterEach(function(){
delete global.test;
});
it ('might work with global', function(){
main.exec();
})
});
Finally, this is test/test2.js:
var should = require('should');
var main = require('../lib/main');
global.test = {third: 3};
describe('some test', function(){
it ('messes up global', function(){
main.exec();
})
});
I expect that the first test would output {another:2} and the second would print {third: 3}. Indeed, this is the behavior I get when I run each test independently. e.g.
jeff#ubuntu:~/workspace/mocha-test$ mocha test/test2.js
{ third: 3 }
․
1 passing (6ms)
However, when running both test with npm packages should and mocha (1.16.1), I get the following output:
jeff#ubuntu:~/workspace/mocha-test$ mocha
{ another: 2 }
․․
1 passing (6ms)
1 failing
1) some test messes up global:
ReferenceError: test is not defined
at Object.exports.exec (/home/jeff/workspace/mocha-test/lib/main.js:3:15)
at Context.<anonymous> (/home/jeff/workspace/mocha-test/test/test2.js:8:10)
at Test.Runnable.run (/usr/lib/node_modules/mocha/lib/runnable.js:211:32)
at Runner.runTest (/usr/lib/node_modules/mocha/lib/runner.js:355:10)
at /usr/lib/node_modules/mocha/lib/runner.js:401:12
at next (/usr/lib/node_modules/mocha/lib/runner.js:281:14)
at /usr/lib/node_modules/mocha/lib/runner.js:290:7
at next (/usr/lib/node_modules/mocha/lib/runner.js:234:23)
at Object._onImmediate (/usr/lib/node_modules/mocha/lib/runner.js:258:5)
at processImmediate [as _immediateCallback] (timers.js:330:15)
test2.js should be structured like this:
describe('some test', function(){
before(function (){
global.test = {third: 3};
});
it ('messes up global', function(){
main.exec();
})
});
travisjeffery on the GitHub issue mentioned in the comment explains:
mocha loads the files and then runs the suites, to reliably setup your tests the setup should be within the suite.
As #SB points out, this may not be amenable to sharing things like global variables across tests.

Categories