Undefined when trying to use Spy - node.js

Using my code:
it('should start application only once', function(done){
var spy = sinon.spy(server, 'startup');
var calledOnce = spy().calledOnce;
calledOnce.should.be.true;
done();
});
I get the error:
Cannot read property should of undefined.
The calledOnce variable is undefined. I'm doing something wrong in how I setup the spy and use it. How can I fix this?
Startup is a method in my object that I exported from a server.js file.

If you want to see if a particular function/method has been called, you need to spy on it before it gets called (otherwise the spy won't know about it):
var server = ...
var spy = sinon.spy(server, 'startup');
server.startup(...);
spy.calledOnce.should.be.true;

Related

How to mock HMSLocation with jest

I'm trying to mock the #hmscore/react-native-hms-location with jest. The function that one of my providers uses is HMSLocation.FusedLocation.Native.hasPermission(), but in one of my test I always get the following:
TypeError: Cannot read property 'Native' of undefined at call (C:\laragon\www\qmy-project\providers\LocationProvider.js:65:57)
I've tried to mock all the Library like this:
jest.mock('#hmscore/react-native-hms-location');
Even like this another way:
jest.mock('#hmscore/react-native-hms-location', () => {
const original = jest.requireActual('#hmscore/react-native-hms-location');
return original;
});
Always is the same. Any help please?

How can I import a JS file with window object references in Node.js?

I have a JS file code.js that will be loaded with a website containing code like the following:
window.someObject = window.someObject || {};
window.someObject.someFunction= function(aCondition) {
if (aCondition) someExternalObject.someFunc2();
};
setTimeout(window.someObject.someFunction, 1000);
I can't change this code.
I want to write a unit test for this, so my test file would look something like this:
const expect = require('chai').expect;
var rewire = require('rewire');
var codeModule = require('./path/to/file/code.js');
describe('Test code.js', () => { //Using Mocha.js
//Stub someObject.someFunction
//Test stub with expect()
})
//MORE CODE
This results in ReferenceError: window is not defined since there is no window object in Node.
The reason I'd want to import that module is that I'd want to mock someObject.someFunction for my test.
How can I deal with references to browser APIs like the window object when testing with Node?
Do I need to require a package like this before?
I'm pretty new to this so bear with me if I have some misconceptions here.
Before you import the file do this.
window = window || {}
It will define the window object in the global namespace, but of course with none of the good stuff you get in a browser.

TypeError: Connot read property 'render' of undefiend while testing a js on node js using mocha and chai

I am doing some testing on my js function and it is my first time doing this and I am getting an error of:
TypeError: Cannot read property 'render' of undefined
I am using chai and mocha. Here is my test code
test1.test.js
it('should return all the data based on the given appname' , function () {
assert.isArray(acc.fetchData().getKeys());
})
This is what on my js function:
exports.fetchData = function (req, res) {
'use strict';
res.render('pages/test1', {
test: a.getKeys(),
arrayToPull: rootValueCombination
});
};
I tried using supertest but I have no luck. I used istanbul as a code coverage which is a bit odd as i am getting 100% but I am getting failed on mocha test.
You are not passing a parameter to fetchData
assert.isArray(acc.fetchData().getKeys());
and res is the second parameter of the function. You need to pass the correct variable to the function, the one which has a render function.

nodeJS proxyquire overwrite specific function of a require

I am currently testing a module in isolation using proxquire to overwrite a require of this module.
Overwriting a path of a require works fine with proxyquire. For example:
var bar = require('./bar');
But can you use proxyquire also to overwrite just a specific function of a module which is required in the module to test? So something like:
var bar = require('./foo').bar();
I need to stay at proxyquire for this since I am using it for mocking a http-request happening in another layer of the architecture. But in case of the test I need to mock the time for "now" in the module as well.
So currently I have this:
var uraStub = sendMockRequest(paramListOfCheckin, queryList);
var setNowStub = function(){ return 1425998221000; };
var checkin = proxyquire('../src/logic/logicHandlerModules/checkin', {
'../../persistence/ura' : uraStub,
'./checkin.setNow' : setNowStub
});
checkin.checkin(...)
The implementation of setNow is:
var setNow = function(){
return new Date().getTime();
};
var checkin = function (...) {
var now = require('./checkin').setNow();
Obviousley './checkin.setNow' : setNowStub in proxyquire doesn't work, since this is the wrong path. But using './checkin'.setNow() : setNowStub also doesn't work because of wrong syntaxis in the object-definition.
Any suggestions?
Thanks in advance!
What you are looking for is the noCallThru() and callThru() methods. https://github.com/thlorenz/proxyquire#preventing-call-thru-to-original-dependency
By default proxyRequire will call through to the mocked dependency which will allow you to pick the methods that you want to overwrite with your own custom function.
So if a dependency in the path '../foo' has a method bar() and fooBar() you would be able to mock out just bar by doing.
proxyquire.callThru();
var fooFunc = proxyquire('../foo', {
bar: () => return 'bar'
})
Now bar() will hit your custom overwritten funtion while fooBar() will be called as normal.

Jasmine spies only detect calls on methods called on Node.js exports object

I'm trying to spy on dependencies in a Node.js module from within a Jasmine spec, and I'm encountering some weird behaviour.
Jasmine spies on a method that resides in an object exposed by the exports object in the module. When I call the spied-on method in the module using
exports.umap()
the spy detects it. But when I call it in the module using a variable name I assigned to the same method
var umap = exports.umap
umap()
the spy doesn't detect it.
This seems weird to me given that var umap refers to the same method as exports.umap. Anyone have any ideas why this is? Code below.
(The whole reason I'm doing this is that I want to stub my module's dependencies without the need to design the module as a class and use dependency injection.)
// mapper.js
exports.umap = require('underscore').map;
var umap = exports.umap;
function map () {
return exports.umap([1,2,3], function(el) {console.log(el);return el * 2});
// umap() goes unnoticed by the spy
// return umap([1,2,3], function(el) {console.log(el);return el * 2});
}
exports.map = map;
.
// mapper_spec.js
var mapper = require ('../../lib/mapper');
var map = mapper.map;
describe('mapper', function() {
describe('map', function() {
it('calls umap', function() {
var mapped;
spyOn(mapper, 'umap').and.callThrough();
mapped = mapper.map();
expect(mapper.umap).toHaveBeenCalled();
expect(mapped).toEqual([2,4,6]);
});
});
});
UPDATE
I'm still curious about this issue, however https://www.npmjs.org/package/proxyquire made my whole "spying-on-things-attached-to-export-object" strategy moot.

Resources