Unit test for node js - node.js

I am new to nodejs, and need to write unit test for a node project. I try to learn mocha and there are two questions:
when I write unit test for function A, in A it also use function B, so how can I mock an output for B?
how can I unit test these endpoints in app.js. like app.get, app.put.
can someone give me some suggestions or simple examples?
Can someone also give me some advice on writing unit test for nodejs, thanks so much.
Thanks so much everyone.

Answering Q1,
If the output of b method is used in a metheod, then you can make the test of b method first.
Otherwise you can prepare result of b in before section of your test method and use it in a method.
It depends on your approach of testing.
Answering Q2 -
You can use superagent for sending get or post request ...
Some code examples ...
require('should');
var assert = require("assert");
var request = require('superagent');
var expect = require('expect.js');
then,
describe('yourapp', function(){
before(function(){
// function start
start your server code
// function end
})
describe('server', function(){
describe('some-description', function(){
it('should return json in response', function(done){
request.post('http path')
.send(JSON.parse("your json"))
.end(function(res){
expect(res).to.exist;
expect(res.status).to.equal(200);
expect(res.text).to.contain('ok');
done();
});
})
});
})
after(function(){
//stop your server
})
});
Here done is an important aspect in a unit testing component for asynchronous method testing.
Some reference -
superagent
this blog post
Hope this will help you,
Thanks

Answering Q1,
If the funcitons in different modules,
You can use a mock tool : fremock
Using freemock You can do this:
your code
//function a exports in the module named mA
function a(){
return "1";
}
//function a exports in the module named mB
function b(){
a();
}
test code
var freemock = require('freemock');
freemock.start()
var mock_b = freemock.getMock('mB');
mock_b.setMethod({
"a":{
willReturn:"1"
}
})
freemock.end();
Some advice:
Mocha is good test framework for node.js .
For example,
Assert tool: should.js
Code coverage tool:istanbul
...
Mocha combines all this tools;
Here is a demo using Mocha:
your code(filename:mA.js)
//in the module named mA
function a(){
return true;
}
test code(filename:testmA.js)
var should = require('should');
beforeEach(function(){
//do something before testing
});
afterEach(function(){
//do something after testing
});
describe("test",function(){
describe("test1",function(){
it("if true",function(){
var mA = require('./mA');
var result = mA.a();
should.ok(result);
});
it("if false",function(){
//other test
});
});
describe("test2",function(){
it("test2-1",function(){
//other test
})
})
})
We should need run.js to start the test:
//run.js
var Mocha = require('mocha');
var mocha = new Mocha;
mocha.addFile(__dirname+'/test/testmA.js')
mocha.run();
The project dir tree is:
|- run.js
|
|- mA.js
|
|- test - testMA.js
Finally
Run this command:
istanbul cover run.js
Hope you enjoy!

I am recently involved in a node project where I have to run unit tests.
Eventually I wrote a small script runner for karma using NW.JS
This allowed me to access all node modules and run my tests on the server itself. I uploaded this project to github, Narma.
Right now it was only tested on a Mac

Related

Writing mocha test for nodejs

I am a beginner to nodejs, I need to know how to write a mocha test for nodejs for variable definitions.
for example,
if i had a object like this,
var objectName = {
fileName : '',
filePath : ''
}
Then how can write a mocha test for this variable definition. Please help me to write a test code. Thanks in advance!
I don't test this kind of stuff usually, but can make something like (using chai.expect) :
var obj = {
name:''
};
describe('My object definition', function(){
it('should give me an empty name', function(){
expect(obj.name).to.equals('');
});
});

Why are the nightmare.js examples not working?

var Nightmare = require('nightmare');
var expect = require('chai').expect; // jshint ignore:line
describe('test yahoo search results', function() {
it('should find the nightmare github link first', function*() {
var nightmare = Nightmare()
var breadcrumb = yield nightmare
.goto('http://yahoo.com')
.type('input[title="Search"]', 'github nightmare')
.click('.searchsubmit')
.wait('.url.breadcrumb')
.evaluate(function () {
return document.querySelector('.url.breadcrumb').innerText;
});
expect(breadcrumb).to.equal('github.com');
});
});
Why does this test always evaluate to true?
This test evaluates to true even if I change the comparison value. If I add a console.log before the expect, it does not print, which makes me thing the test is never being evaluated and that a null response is true for chai. I am running node v4.2.2, and the latest versions of nightmare and expect. I run the test from the terminal using mocha index.js (the name of this file).
function* and yield is a ES2015 feature called Generators.
There's a additional note after the example on the README:
Please note that the examples are using the mocha-generators package for Mocha, which enables the support for generators.
So you need to install the package and add this to your code:
require('mocha-generators').install();

How to use Jasmine to test if an instance is created?

Hi Am new to using Jasmine. The issue is as follows: I have a number of modules, managed through RequireJS. Now a module A creates an instance of another module B in it. Is it possible to use Jasmine to test whether an instance of B is being created in A? To convey a clearer idea of the code, we have:
//In module A
define(['B',],function(B){
function test(){
var newTest = new B();
};
return {test: test};
});
Now, how do i use Jasmine to test that module A indeed, creates an instance of module B? Thanks in advance!
Regards
Here's one way to check the type of an object in a Jasmine test:
describe('ChocolateFactory', function() {
it('creates an instance of Chocolate', function() {
var factory = new ChocolateFactory();
var chocolate = factory.makeChocolate();
expect(chocolate instanceof Chocolate).toBe(true);
});
});

Locomotive.js throws error upon calling "locomotive.boot"

I'm trying to write tests on my locomotive.js application, literally copy/pasting code from some examples on the internet. Even so, whenever I run my tests, I get an error saying
TypeError: string is not a function
When I check the number of arguments expected by locomotive.boot (using locomotive.boot.length), it says 2... But in every single example online (go ahead, google it) the documentation seems to say 3. Does anyone know what I'm doing wrong?
Here's my code:
var locomotive = require('locomotive'),
should = require('should'),
request = require('supertest');
var app, server;
describe('Application', function() {
before(function(done) {
locomotive.boot( __dirname+"/..", "test", function(err, express) {
if (err) throw err;
app = this;
express.listen(4000, '0.0.0.0', function() {
var addr = this.address();
console.log('Server started. [Env: '+SOPS.conf.get('app:environment')+'] [Addr: '+addr.address+'] [Port: '+addr.port+']');
done();
});
server = express;
});
});
it('should have started the app', function(){
should.exist(app);
should.exist(express);
});
});
There are 2 branches on the LocomotiveJS repo:
- 0.3.x (https://github.com/jaredhanson/locomotive/tree/0.3.x)
- master (https://github.com/jaredhanson/locomotive/tree/master)
If you're using version 0.3.x your code should work, the function declaration actually shows 4 arguments: dir, env, options, callback
you can have a look at the function definition here (Locomotive.prototype.boot): 0.3.x/lib/locomotive/index.js
As of version 0.4.x (branch master) the boot function only accepts 2 arguments: env, callback
the function definition for this branch is here (Application.prototype.boot): master/lib/application.js
so your code should look something like:
locomotive.boot( "test", *yourcallback* );
Hope this helps.

Mocha and ZombieJS

I'm starting a nodejs project and would like to do BDD with Mocha and Zombiejs. Unfortunately I'm new to just about every buzzword in that sentence. I can get Mocha and Zombiejs running tests fine, but I can't seem to integrate the two - is it possible to use Mocha to run Zombiejs tests, and if so, how would that look?
Just looking for "hello world" to get me started, but a tutorial/example would be even better.
Thanks!
Assuming you already have installed mocha, zombie and expect.js according to instructions, this should work for you:
// Put below in a file in your *test* folder, ie: test/sampletest.js:
var expect = require('expect.js'),
Browser = require('zombie'),
browser = new Browser();
describe('Loads pages', function(){
it('Google.com', function(done){
browser.visit("http://www.google.com", function () {
expect(browser.text("title")).to.equal('Google');
done();
});
});
});
Then you should be able to run the mocha command from your root application folder:
# mocha -R spec
Loads pages
✓ Google.com (873ms)
✔ 1 tests complete (876ms)
Note: If your tests keep failing due to timeouts, it helps to increase mocha's timeout setting a bit by using the -t argument. Check out mocha's documentation for complete details.
I wrote a lengthy reply to this question explaining important gotchas about asynchronous tests, good practices ('before()', 'after()', TDD, ...), and illustrated by a real world example.
http://redotheweb.com/2013/01/15/functional-testing-for-nodejs-using-mocha-and-zombie-js.html
if you want to use cucumber-js for your acceptance tests and mocha for your "unit" tests for a page, you can use cuked-zombie (sorry for the advertising).
Install it like described in the readme on github, but place your world config in a file called world-config.js
`/* globals __dirname */
var os = require('os');
var path = require('path');
module.exports = {
cli: null,
domain: 'addorange-macbook': 'my-testing-domain.com',
debug: false
};
Then use mocha with zombie in your unit tests like this:
var chai = require('chai'), expect = chai.expect;
var cukedZombie = require('cuked-zombie');
describe('Apopintments', function() {
describe('ArrangeFormModel', function() {
before(function(done) { // execute once
var that = this;
cukedZombie.infectWorld(this, require('../world-config'));
this.world = new this.World(done);
// this inherits the whole world api to your test
_.merge(this, this.world);
});
describe("display", function() {
before(function(done) { // executed once before all tests are run in the discribe display block
var test = this;
this.browser.authenticate().basic('maxmustermann', 'Ux394Ki');
this.visitPage('/someurl', function() {
test.helper = function() {
};
done();
});
});
it("something on the /someurl page is returned", function() {
expect(this.browser.html()).not.to.be.empty;
});

Resources