I'm currently navigating my way through sinon and mocha, working on the code and test provided below. My goal is to test the findAll()
method without triggering an http request.
However, I've encountered an error with the current setup:
[TypeError: Cannot read property 'on' of undefined]
. I'm unsure about how to properly stub or spy the .on
event.
/modles/user.js
'use strict';
const Rest = require('restler');
const Q = require('q');
class User {
static findAll() {
return Q.promise(function(resolve, reject) {
Rest.get('<SOME URL FOR DATA>')
.on('complete', function(data, response) {
if(data instanceof Error) {
return reject(data);
}
return resolve(data);
});
});
}
...
}
module.exports = User;
/test/models/user.js
'use strict';
const expect = require('chai').expect;
const sinon = require('sinon');
const Rest = require('restler');
describe('User model', function() {
var User;
beforeEach(function() {
this.get = sinon.stub(Rest, 'get');
});
afterEach(function() {
Rest.get.restore();
})
it('should not blow up when requiring', function() {
User = require('../../models/user');
expect(User).to.not.be.undefined;
});
describe('findAll()', function() {
it('should return all users', function() {
const expected = [{personId: 1234}, {personId: 1235}];
User.findAll()
.then(function(result) {
console.log('result = ', result);
})
.fail(function(err) {
console.log('err = ', err);
// KEEPS DISPLAYING THIS: err = [TypeError: Cannot read property 'on' of undefined]
})
});
});
});