First test with mocha - javascript

I mactually trying to run my first unit test with mocha using this code :
var assert = require('assert');
var returnCool = function () {
return 1;
}
describe("Array contains", function () {
it('should return-1 when the value is not present', function () {
returnCool().should.equal(1);
});
});
The problem is that my code is actually failing everytime.
I tried with the sample in mocha website :
describe('Array', function(){
describe('#indexOf()', function(){
it('should return -1 when the value is not present', function(){
[1,2,3].indexOf(5).should.equal(-1);
[1,2,3].indexOf(0).should.equal(-1);
})
})
})
And it fails too.
What am I doing wrong ?
Thanks for advance

Looks like you are not calling your assertion library. You are currently calling .should() on an integer

You have included an assert library but are using should - style asserts. Either include should.js or use assert-style asserts (assert.equal([1,2,3].indexOf(5), -1))

Related

Unit Testing with Jasmine - Can not spyOn mocked method

I am writing a javascript library that calls a method on another js lib.
Most of the time i would create a mock function of the 3rd party library and spy on it. However, it doesn't seem to work.
For example:
mymain.js
export const checkForExternalFunc = () => {
try {
return com.externalFunc
} catch (error) {
return false
}
}
mymain_spec.js
import { checkForExternalFunc } from './src';
describe('checkForExternalFunc', () => {
let com = com || {};
com.externalFunc = function () {
return true;
};
it('return the function when com.externalFunc is present', () => {
spyOn(com, "externalFunc");
let check = checkForExternalFunc();
expect(check).toBe(jasmine.Any(function));
});
})
and this would give me an error
ReferenceError: com is not defined
Function in 3rd part library
var com = com || {};
com.externalFunc = function () {
// return something
};
Any suggestion how i can approach this? Also i have researched a little on Stub with Sinon but not sure how to use it properly. Any help will be appreciated. Thanks!!
Note: I setup project with webpack + babel, karma, jasmine.
Thanks #AdityaBhave for pointing out. I only need to make sure my mock function and the actual one are actually the same. Please see comment above.

TypeError: undefined not a constructor when using beforeEach in jasmine test

I have run into a problem when writing unit tests in jasmine which I have managed to distill down to a a very basic test scenario:
describe('weird shit', function () {
var myVal;
beforeEach(myVal = 0);
it('throws for some reason', function () {
expect(myVal).toBe(0);
});
});
and this throws a TypeError:
Test 'weird shit:throws for some reason' failed
TypeError: undefined is not a constructor (evaluating 'queueableFn.fn.call(self.userContext)') in
file:///C:/USERS/9200378/APPDATA/LOCAL/MICROSOFT/VISUALSTUDIO/14.0/EXTENSIONS/SKJV5WFA.151/TestFiles/jasmine/v2/jasmine.js (line 1886)
run#file:///C:/USERS/9200378/APPDATA/LOCAL/MICROSOFT/VISUALSTUDIO/14.0/EXTENSIONS/SKJV5WFA.151/TestFiles/jasmine/v2/jasmine.js:1874:20
execute#file:///C:/USERS/9200378/APPDATA/LOCAL/MICROSOFT/VISUALSTUDIO/14.0/EXTENSIONS/SKJV5WFA.151/TestFiles/jasmine/v2/jasmine.js:1859:13
queueRunnerFactory#file:///C:/USERS/9200378/APPDATA/LOCAL/MICROSOFT/VISUALSTUDIO/14.0/EXTENSIONS/SKJV5WFA.151/TestFiles/jasmine/v2/jasmine.js:697:42
execute#file:///C:/USERS/9200378/APPDATA/LOCAL/MICROSOFT/VISUALSTUDIO/14.0/EXTENSIONS/SKJV5WFA.151/TestFiles/jasmine/v2/jasmine.js:359:28
fn#file:///C:/USERS/9200378/APPDATA/LOCAL/MICROSOFT/VISUALSTUDIO/14.0/EXTENSIONS/SKJV5WFA.151/TestFiles/jasmine/v2/jasmine.js:2479:44
if I removed the beforeEach then it works fine:
describe('weird shit', function () {
var myVal =0;
it('throws for some reason', function () {
expect(myVal).toBe(0);
});
});
Which I do not understand, the beforeEach is very basic, please help.
beforeEach accepts a function, you passed the result of myVal = 0, which is 0, which isn't a function.
beforeEach(myVal = 0);
Replace the above code with the following:
beforeEach(function() {
myVal = 0;
});
Refer the documentation of jasmine 2.5 here for more information.
beforeEach(function(){myVal = 0;});
Purpose of beforeEach() is to execute some function that contains code to setup your specs.
In this case, it is setting variable myVal = 0
You should pass a function to beforeEach() like below:
beforeEach(function() {
myVal = 0
});
in order to successfully setup your variable.

Using external class during client side Mocha unit testing

I am running unit tests on a javascript class using Mocha using the follow methodology, firstly the test:
var base = require('../moduleone.js');
describe("some test", function() {
it("description", function() {
var check = base.toBeTested(dummyValue)
//test is here ...
});
});
the moduleone.js containing function to be tested:
function toBeTested(category){
//below I calling an assert function defined in moduletwo
//works fine when running in browser
assert(type(category)=='string','category is string type');
//more code..
return something
module.exports.toBeTested = toBeTested;
moduletwo.js:
function assert(outcome, description) {
//see code.tutsplus.com quick and easy javascript testing with assert
var li = outcome ? 'pass' : 'fail';
if (li == 'fail') {
console.log('FAIL: '+description);
}
else {
console.log('PASS: '+description);
}
}
The issue I have is mocha doesn't know anything about moduletwo and when the moduleone function calles the function in moduletwo mocha throws a ReferenceError: assert is not defined. How can I link all my dependencies so that mocha can see them?
In your moduleone.js be sure that you are requireing moduletwo.js to bring your assert function into scope for moduleone.js. Otherwise, you get a ReferenceError, not for any reasons with mocha, but because moduleone does not have access to assert.
// moduletwo.js
function assert(outcome, description) { /* your functionality */ }
module.exports = assert
// moduleone.js
var assert = require('./moduletwo')
function toBeTested(category) { /* your functionality that uses assert */ }
module.exports.toBeTested = toBeTested
Now, with regards to that tutorial. If you are following it to learn how to make an easy assert module, that is fine. But if you are trying to test some code that does something else, consider using an existing assertion library like chai. For example:
// example.test.js
var expect = require('chai').expect
var isValidCategory = require('./is-valid-category')
describe('isValidCategory(category)', function () {
it('validates string categories', function () {
expect(isValidCategory('A String Category')).to.be.true
})
it('does not validate non-string categories', function () {
expect(isValidCategory(['an', 'array', 'somehow'])).to.be.false
})
})
// is-valid-category.js
module.exports = function isValidCategory(category) {
return typeof category === 'string'
}

Test a function which uses document properties in qunit

I have a function like this which I would like to write a unit test for :
function A () {
var x = document.referrer;
//Do something with 'a'
}
I would like to write a unit test, to test this function. I'm using QUnit with sinon.js for stubs and mocks. Is there a way for me to mock the document object so that I can provide a value for the referrer and test my logic? I tried assigning a value to document.referrer in my setup function, but that didn't work
Update
This is the test which I'm trying :
module("Verify Referrer", {
setup : function () {
this.documentMock = sinon.mock(document);
this.documentMock.referrer = "http://www.test.com";
},
teardown : function () {
this.documentMock.restore();
}
});
test("UrlFilter test url in white list", function() {
equal(document.referrer, "http://www.test.com");
});
I also tried using stub

Jasmine object “has no method 'andReturn'”

Beginner with Jasmine, very first attempt with Jasmine Spies. I thought I was mimicking the format displayed here (search: "andReturn"), but I'm getting an error that I can't work out:
TypeError: Object function () {
callTracker.track({
object: this,
args: Array.prototype.slice.apply(arguments)
});
return spyStrategy.exec.apply(this, arguments);
} has no method 'andReturn'
No clue what I'm doing wrong. Here's my Spec:
describe('Die', function() {
it('returns a value when you roll it', function() {
var die = Object.create(Die);
spyOn(Math, 'random').andReturn(1);
expect(die.roll()).toEqual(6);
});
});
And the corresponding JS:
var Die =
{
roll: function() {
return Math.floor(Math.random() * 5 + 1);
}
}
Thanks for the help!!!
jasmine 2.0 changed some of the spy syntax. jasmine 2.0 docs
spyOn(Math, 'random').and.returnValue(1);
try this
spyOn(Math, 'random').and.returnValue(1);
I made a jasmine test where I show this kind of mock. andReturn seems to be working. http://jsfiddle.net/LNWXn/
it("has a value of 1 with and return", function() {
spyOn(Math, 'random').andReturn(1);
expect(Math.random()).toBe(1);
});
You have to keep in mind that it's only mocked for the scope of the test.
Here's one with your example that seems to pass. http://jsfiddle.net/LNWXn/2/
Hope this helped!
use and.returnValue() insted of andReturn()

Categories

Resources