How to unit test promise with sinon in my case? - node.js

I am trying to start a stub in unit test for my app.
I have something like this in my file.
var sinon = require('sinon'),
should = require('should');
require('sinon-stub-promise');
describe('test unit Tests', function(){
describe('My first test', function(){
it('should test a promise', function(){
sinon.stub().resolves('foo')().then(function (value) {
console.log('test');
assert.equal(value, 'not foooo')
})
})
});
My problem is I can't seem to trigger the assert.equal error. I can see the 'test' in the output when run the test. However, the test should fail because the value should be foo and not 'not foooo'. For some reason it passed. I am not sure the reason. Can someone help me about it? Thanks a lot!

you need to return the promise so mocha waits:
describe('test unit Tests', function(){
describe('My first test', function(){
it('should test a promise', function(){
return sinon.stub().resolves('foo')().then(function (value) {
console.log('test');
assert.equal(value, 'not foooo')
})
})
})
});

Related

How to test promise rejection with Mocha and Chai in Node?

I am trying to test my services and dao using Mocha and Chai. But, in Istanbul coverage, I am getting the 'reject' lines as red. Here is the code for a sample testing method.
describe('findAllCategories()', function() {
it('should return all categories', function() {
var stub = sinon.stub(categoryDao, 'findAllCategories');
stub.callsFake(() => {
return Promise.resolve(cat);
});
categoryService.findAllCategories().then(response => {
assert.length(response, 1);
}).catch(isError)
.then((err) => {
console.log(err);
assert.isDefined(err);
});
})
});
Now, when I'm logging the error, it is showing "TypeError: assert.length is not a function".
Any way out?
The assert-library does not have a function length, but instead you can use lengthOf() (see https://www.chaijs.com/api/assert/ for more information):
assert.lengthOf(response, 1);

Context in mocha test is undefined

So I'm using mocha and node to test some apis. I have a test that goes
import { describe, before, it, xit } from 'mocha';
describe('test my scenarios dude', () => {
before('do all my pre-test stuff', () => {
const blah = blah;
});
it('tests my really useful test', () => {
const testName = this.test.ctx.currentTest.fullTitle();
});
});
The 'this' is undefined though. How can I get the test name?
https://mochajs.org/#arrow-functions
as docs says Passing arrow functions (“lambdas”) to Mocha is discouraged
use function instead
describe('test my scenarios dude', function() {
before('do all my pre-test stuff', function() {
const blah = blah;
});
it('tests my really useful test', function() {
const testName = this.test.ctx.currentTest.fullTitle();
});
});
also you can read more about arrow functions here. they don't have this

Why won't these chai tests fail?

We have some simple "is this really working" chai tests of an electron app using spectron and WebdriverIO. The example code we started with is from
https://github.com/jwood803/ElectronSpectronDemo as reported in https://github.com/jwood803/ElectronSpectronDemo/issues/2, the chai-as-promised tests are not catching mismatches, so I thought I would add some additional tests to find out why Chai is not failing tests where the electron app has text that doesn't match the expected unit test text.
Let's start with something really simple, the rest of the code is at https://github.com/drjasonharrison/ElectronSpectronDemo
describe('Test Example', function () {
beforeEach(function (done) {
app.start().then(function() { done(); } );
});
afterEach(function (done) {
app.stop().then(function() { done(); });
});
it('yes == no should fail', function () {
chai.expect("yes").to.equal("no");
});
it('yes == yes should succeed', function () {
chai.expect("yes").to.equal("yes");
});
The first unit test fails, the second succeeds.
And when we put the assertion into a function this still detects the failure:
it('should fail, but succeeds!?', function () {
function fn() {
var yes = 'yes';
yes.should.equal('no');
};
fn();
});
So now into the world of electron, webdriverio, and spectron, the application title is supposed to be "Hello World!", so this should fail, but it passes:
it('tests the page title', function () {
page.getApplicationTitle().should.eventually.equal("NO WAY");
});
Hmm, let's try a more familiar test:
it('should fail, waitUntilWindowLoaded, yes != no', function () {
app.client.waitUntilWindowLoaded().getTitle().then(
function (txt) {
console.log('txt = ' + txt);
var yes = 'yes';
yes.should.equal('no');
}
);
});
Output:
✓ should fail, waitUntilWindowLoaded, yes != no
txt = Hello World!
It succeeds? What? Why? How?
Found it! If you look at https://github.com/webdriverio/webdriverio/blob/master/examples/standalone/webdriverio.with.mocha.and.chai.js
you will see that you need to return the promise from each of the tests. This is typical for async chai/mocha tests:
it('tests the page title', function () {
return page.getApplicationTitle().should.eventually.equal("NO WAY");
});
If you do that, then the chai test is actually correctly evaluated.

Mocha Chai timeout error on 'expect' statement failure

I'm getting unexpected timeout behavior using Mocha and Chai's 'expect' statement when a test fails.
The code:
require('./lib/test-env.js');
const expect = require('chai').expect;
const estimateQuery = require('../lib/estimate-query-helper.js');
describe('testing auth routes', function() {
describe('testing estimate query helper', function() {
it('should return an average daily rate and occupancy rate', (done) => {
estimateQuery.getEstimate()
.then(result => {
expect(result[0]['avg(`Average Daily Rate`)']).to.be.a('number');
expect(result[0]['avg(`Occupancy Rate LTM`)']).to.be.a('number');
done();
});
});
});
});
When I run this with correct expect values, test passes w/no timeout (and I've checked to see the returned values are all correct). But when I change 'number' to (for example) 'string' on either of the statements, rather than failing and throwing 'Expected ..., Actual ..." error, it times out. I've checked out the docs and Chai's open issues and can't find an answer.
Thanks very much in advance for your help.
That's because the promise is catching the error that's thrown by the failing expectation, resulting in the done callback not being called.
Mocha understands promises, so you can return a promise instead of using a callback:
describe('testing auth routes', function() {
describe('testing estimate query helper', function() {
it('should return an average daily rate and occupancy rate', () => {
return estimateQuery.getEstimate()
.then(result => {
expect(result[0]['avg(`Average Daily Rate`)']).to.be.a('number');
expect(result[0]['avg(`Occupancy Rate LTM`)']).to.be.a('number');
});
});
});
});
Any failed expectations will then result in the promise being rejected and the test being reported as failing.
Alternatively, you could stick with the done callback and add a catch:
describe('testing auth routes', function() {
describe('testing estimate query helper', function() {
it('should return an average daily rate and occupancy rate', (done) => {
estimateQuery.getEstimate()
.then(result => {
expect(result[0]['avg(`Average Daily Rate`)']).to.be.a('number');
expect(result[0]['avg(`Occupancy Rate LTM`)']).to.be.a('number');
done();
})
.catch(done);
});
});
});

Mocha Test #getImpact "before all" hook: Error: timeout of 2000ms exceeded

I want to test a module which runs a jar file and gives me back a result.
The problem is that the jar file is bound to take about 5 minutes to execute and give the result, because of which I get the error
Callgraph_class_traversal #getImpact "before all" hook:
Error: timeout of 2000ms exceeded
My testing code is
describe("Callgraph_class_traversal", function() {
describe("#getImpact", function() {
var gerritData
var revert;
var result;
var resMock = function() {};
var updateDatabaseMock = function(res, _gerritData) {
gerritData = _gerritData;
res();
};
before(function(done) {
callgraph_class_traversal.__set__({
updateDatabase: updateDatabaseMock,
up: upMock
});
callgraph_class_traversal.getImpact(methodsChanged, done, gerritId);
});
it('should get correct api paths', function() {
assert.deepEqual(gerritData.apiResult.paths, expectedGerritData.apiResult.paths);
});
it('should get correct api objects', function() {
assert.deepEqual(gerritData.apiResult.names, expectedGerritData.apiResult.names);
});
it('should get correct cts paths', function() {
assert.deepEqual(gerritData.ctsResult.paths, expectedGerritData.ctsResult.paths);
});
it('should get correct cts names', function() {
assert.deepEqual(gerritData.ctsResult.names, expectedGerritData.ctsResult.names);
});
after(function() {
// revert();
});
});
});
callgraph_class_traversal is the module which I want to test.
I am using rewire and assert to test my code.
Please help me with this

Resources