test works with jasmine-node, but not and with jasmine - javascript

I have a object that is subscribed to the uncaught error event and I am trying to test its behaviour. First I tried with jasmine-node, but now when I am trying to go with jasmine I found trouble. Could anyone help me.
describe('Constructor tests', function () {
it('error is passed to the callback', function (done) {
const error = new Error("testError-0");
let errorHandler = new AllErrorHandler((arg1) => {
expect(arg1).toBe(error);
errorHandler.dispose();
done();
});
setTimeout(() => {
throw error;
}, 0)
});
Thanks in advance.

I got this working when executed directly via jasmine when the jasmine ./tests/alLErrorException.spec.js command is run. The following changes were required:
Always setup the listeners, even when the _callback should not be executed.
constructor(callback, startListening = true) {
if (!callback) {
throw new Error("Missing callback function");
}
this._callback = callback;
this._listening = startListening;
this._setupEvents();
}
Add a function to intercept uncaughtException events and to call the _callback if we are _listening:
_handler() {
if(this._listening) {
this._callback.apply(null, arguments);
}
}
Remove all other uncaughtException event handlers in _setupEvents:
_setupEvents(attatch = true) {
this._listening = attatch ? true : false;
if (attatch) {
if (typeof window !== "undefined") {
window.addEventListener("error", this._callback);
} else {
// Added this line
process.removeAllListeners('uncaughtException');
process.addListener('uncaughtException', this._handler.bind(this));
}
} else {
if (typeof window !== "undefined") {
window.removeEventListener("error", this._callback);
} else {
process.removeListener('uncaughtException', this._callback);
}
}
}
This is required because jasmine sets up it's own uncaughtException handler and reports an error even though the error was caught by the AllErrorHandler class.
Here is a paste of the full source for the AllErrorHandler class with the required changes.

Related

Javascript testing - function called with specfic argument

I am trying to write a unit test for a function but cannot figure out how to check if it makes a call to a nested function with a specific argument. I am assuming I will need to use sinon alongside chai and mocha for this, but I could really use some help.
The function I would like to test looks like:
function myFunc(next, value) {
if (value === 1) {
const err = new Error('This sets an error');
next(err);
} else {
next();
}
}
I would like to test if next is called with or without the err variable. From what I read so far I should use a spy for this (I think) but how would I use that spy? Looking at this example from the Sinon docs it is unclear to me where PubSub comes from:
"test should call subscribers with message as first argument" : function () {
var message = "an example message";
var spy = sinon.spy();
PubSub.subscribe(message, spy);
PubSub.publishSync(message, "some payload");
sinon.assert.calledOnce(spy);
sinon.assert.calledWith(spy, message);
}
Source: https://sinonjs.org/releases/latest/assertions/
If you have a function like this
function myFunc(next, value) {
if (value === 1) {
const err = new Error('This sets an error');
next(err);
} else {
next();
}
}
The test could look like this
it ('should call the callback with an Error argument', function (done) {
const callback = (err) => {
if (err && err instanceof Error && err.message === 'This sets an error'){
// test passed, called with an Error arg
done();
} else {
// force fail the test, the `err` is not what we expect it to be
done(new Error('Assertion failed'));
}
}
// with second arg equal to `1`, it should call `callback` with an Error
myFunc(callback, 1);
});
so you don't necessarily need sinon for that

Jest: .toThrow matcher does not pass test on Error

I want to test invalid Inputs of a function and expect the function to throw
on that inputs. However the test does not pass but the function still throws the error. Im kind of a beginner with jest so I dont know why that happens.
My function looks like this:
export class MyClass{
static theFunction(tokens){
let result = [];
if (typeof tokens[0] === "string") {
return tokens;
} else {
try {
for(let token of tokens){
result.push(token.text);
}
return result;
} catch (e) {
throw new Error(e); //also tried throw e; and no try/catch aswell
}
}
}
}}
Test.js:
import {MyClass} from './MyClass'
describe('Test the MyClass:', () => {
test('invalid inputs for thefunction()', () => {
expect(MyClass.theFunction(0)).toThrow(/*'TypeError: tokens is not iterable'*/);
//Tried with and without the Error Message
});
});
What am I missing?
Wrap your function in an anonymous function so that Jest can catch the error:
describe('Test the MyClass:', () => {
test('invalid inputs for thefunction()', () => {
expect( () => { MyClass.theFunction(0) } ).toThrow();
});
});
You might want to read the section about toThrow() in the Jest documentation and also check the implementation in the Jest project on Github.

jasmine testing uncaught error event handler

I am having difficulties testing a new package that I am writing with jasmine.
The package idea is to create a listener for error or "uncaughtException" (in node) and give it a callback to work if there is such event.
describe('AllErrorHandler', function () {
it('error is passed to the callback', function () {
const error = new Error("testError");
const callbackError;
let errorHandler = new AllErrorHandler((error) => {
callbackError = error;
})
throw error;
expect(callbackError).toBe(error);
})
})
How can I make this right?
First of all, error is not a function. You need throw error not throw error().
Then the line after you throw is not reachable (unless you wrap the whole thing with try-catch :) which kinda beats the whole point of the test).
You could try something like this. But I'm not 100% this would work.
describe('AllErrorHandler', function () {
it('error is passed to the callback', function (done) {
const error = new Error("testError");
let errorHandler = new AllErrorHandler((arg1) => {
expect(arg1).toBe(error);
done();
});
setTimeout(() => {
throw error;
}, 0)
})
})

Proxy get handler called on evaluation of proxy

I defined a proxy as follows:
const o1 = {
ready: false
};
setTimeout(() => {
o1.ready = true;
}, 1000000000);
const handler = {
get(target, propKey, receiver) {
if (target.ready == false) {
throw new Error('not ready');
} else {
return 'ready'
}
}
};
const proxy = new Proxy(o1, handler);
proxy; // raises 'not ready'
Evaluating proxy raises the error 'not ready', even though it isnt a property access. How do I prevent the error from being raised when the reference to the proxy is evaluated? This causes bugs when requiring without assignment.
It seems to be related to this bug: https://github.com/nodejs/node/issues/10731
The best work around I've found is to specifically ignore the node inspection:
const handler = {
get(target, propKey, receiver) {
if (propKey != util.inspect.custom &&
propKey != 'inspect' &&
propKey != Symbol.toStringTag){
if (target.ready == false) {
throw new Error('not ready');
} else {
return 'ready'
}
}
}
};
Or alternatively if you knew the list of keys you cared about then just check those instead of excluding.
Apparently you're evaluating this in the REPL, where the final proxy; statement makes for the result value of the code and which is logged to the console. Logging it will access the properties, that's expected.
However, you really should not be using a proxy here. A proxy should handle different properties individually, but yours appears to only care about the ready property. A simpler getter would be more appropriate:
const o1 = {
ready: false
};
setTimeout(() => {
o1.ready = true;
}, 1000000000);
const res = { // instead of the `proxy` object
get ready() {
if (o1.ready == false) {
throw new Error('not ready');
} else {
return 'ready'
}
}
};
res.ready // either throws or yields the string "ready"

Event Emitter Javascript

Hi i am a newbie in javascript. I am implementing emitter on function in javascript and i have trouble in testing it using jasmine framework. Below is the function emitter on and code to test the function.
//main.js
Emitter.prototype.on = function (event, listener)
{
if (typeof this.events[event] !== 'object')
{
this.events[event] = [];
}
this.events[event].push(listener);
};
//test.js
describe('#on', () =>
{
it('should subscribe to an event name and be called when
triggered', () =>
{
Emitter.on(EVENT_NAME_ONE, spyFunction);
//Emitter.trigger(EVENT_NAME_ONE);
expect(spyFunction.calls.count()).toBe(1);
});
The above mentioned test fails. I am not sure why. Can someone please help me with this. Thanks.
The error says Emitter.on is undefined. See this thread.
on is defined on Emitter instance.
class Emitter {
constructor() {
console.log('created Emitter!')
}
on(event, callback) {
console.log('on')
}
}
a = new Emitter()
=> created Emitter!
a.on()
=> on
I could solve that error. i had to export the function to the tests and changed the browser to chrome in karma.conf.js file . Now i get this TypeError: Cannot read property 'event_name_one' of undefined. I have it defined
var Emitter = function () {
this.events = {};
var Event_Name_One;
} ;
export function on (event, listener) {
if (typeof this.events[event] !== 'object') {
this.events[event] = [];
}
this.events[event].push(listener);
};
and in test.js
// Testing event names
const EVENT_NAME_ONE = 'event_name_one';
describe('#on', () => {
it('should subscribe to an event name and be called when triggered', () => {
Emitter.on(EVENT_NAME_ONE, spyFunction);
Emitter.trigger(EVENT_NAME_ONE);
expect(spyFunction.calls.count()).toBe(1);
});
I don't understand why i get this error. Can anyone provide help regarding this.thanks.

Categories

Resources