Correct way to unit-test observable stream being fed - javascript

I use this to test that the service adds an item to observable stream of errors.
it('can be subscribed for errors', () => {
let testError = new Error('Some error.');
let called = false;
let subscription = service.onError.subscribe(error => {
called = true;
expect(error).toEqual(testError);
});
/// This makes an error to be added to onError stream
service.setError(testError);
expect(called).toEqual(true);
});
I use the called variable to make sure that the subscription callback was actually called. Otherwise the test would pass when it shouldn't. But it doesn't seem right to me. Also, it wouldn't work if the stream was asynchronous.
Is this a good way to test that? If not, how to do it properly?
EDIT: this is the class that's being tested. It's in typescript, actually.
import { ReplaySubject } from 'rxjs/Rx';
export class ErrorService {
private error: Error;
public onError: ReplaySubject<Error> = new ReplaySubject<Error>();
constructor() {
}
public setError = (error: Error) => {
this.error = error;
console.error(error);
this.onError.next(error);
}
public getError() {
return this.error;
}
public hasError() {
return !!this.error;
}
}

The way you are testing is good. You are:
Checking if the value is correct with expect statement.
Checking the fact the expect statement is being executed.
Especially the last part is important otherwise the expect might not be triggered and the test will falsely pass.

Related

SignalR intercept every incoming message (client side)

I have a question regarding SignalR on the clientside (JS). Is there a way to intercept incoming messages at the clientside? I am working on a chat application with a lot traffic on the socket. I want to be able to execute code (catch errors if any) on every incoming event.
Looking at the docs I can't find any existing solution for this. Is there one?
After a bit of research, this does not seem to be possible.
My first thought for a workaround was using a function to 'pipe' the callback functions through first.
E.G.
private pipeSignal(cb: (arg: any) => void): (arg: any) => void {
const errors = checkForErrors();
if(errors){
return () => {
// Handle error here
};
}
return cb;
}
I then thought setting up the handlers could look as follows:
this.hubConnection.on(
'MyMethod1',
this.pipeSignal((method1Val) => {
console.log(method1Val);
})
);
this.hubConnection.on(
'MyMethod2',
this.pipeSignal((method2Val) => {
console.log(method2Val);
})
);
BUT, this results in the 'pipeSignal' function being called only once when setting up the event listener. Thereafter, it will not be called.
I think the only option here would be to have a function that checks for errors in every event listener callback.
private hasErrors(arg: any): boolean {
const errors = checkForErrors();
if(errors){
// Handle error here
return true;
}
return false;
}
Then in each signal event callback you can try checking for errors like this:
this.hubConnection.on(
'MyMethod1',
(method1Val) => {
if(!this.hasErrors(method1Val)){
// Can continue knowing there are no errors
console.log(method1Val);
}
}
);
UPDATE
Turns out I was close with my 'pipeSignal' function. Rather than running the error logic in the pipeSignal function, I return a function that wraps the error logic and the callback:
private pipeSignal(cb: (arg: any) => void): (arg: any) => void {
return (arg) => {
const errors = checkForErrors();
if(errors){
// handle errors
} else {
// proceed with callback as there are no errors
cb(arg);
}
};
}
Now this can be used as I imagined before:
this.hubConnection.on(
'MyMethod1',
this.pipeSignal((method1Val) => {
console.log(method1Val);
})
);

JavaScript: differences between async error handling with async/await and then/catch

Just wanted to preemptively say that I am familiar with async/await and promises in JavaScript so no need to link me to some MDN pages for that.
I have a function to fetch user details and display it on the UI.
async function someHttpCall() {
throw 'someHttpCall error'
}
async function fetchUserDetails() {
throw 'fetchUserDetails error'
}
function displayUserDetails(userDetails) {
console.log('userDetails:', userDetails)
}
async function fetchUser() {
try {
const user = await someHttpCall()
try {
const details = await fetchUserDetails(user)
returndisplayUserDetails(details)
} catch (fetchUserDetailsError) {
console.log('fetching user error', fetchUserDetailsError)
}
} catch (someHttpCallError) {
console.log('networking error:', someHttpCallError)
}
}
It first makes HTTP call via someHttpCall and if it succeeds then it proceeds to fetchUserDetails and it that succeeds as well then we display the details on Ui via returndisplayUserDetails.
If someHttpCall failed, we will stop and not make fetchUserDetails call. In other words, we want to separate the error handling for someHttpCall and it’s data handling from fetchUserDetails
The function I wrote is with nested try catch blocks which doesn't scale well if the nesting becomes deep and I was trying to rewrite it for better readability using plain then and catch
This was my first atttempt
function fetchUser2() {
someHttpCall()
.then(
(user) => fetchUserDetails(user),
(someHttpCallError) => {
console.log('networking error:', someHttpCallError)
}
)
.then(
(details) => {
displayUserDetails(details)
}, //
(fetchUserDetailsError) => {
console.log('fetching user error', fetchUserDetailsError)
}
)
}
The problem with this is that the second then will run i.e. displayUserDetails even with someHttpCall failing. To avoid this I had to make the previous .catch blocks throw
so this is the updated version
function fetchUser2() {
someHttpCall()
.then(
(user) => fetchUserDetails(user),
(someHttpCallError) => {
console.log('networking error:', someHttpCallError)
throw someHttpCallError
}
)
.then(
(details) => {
displayUserDetails(details)
}, //
(fetchUserDetailsError) => {
console.log('fetching user error', fetchUserDetailsError)
}
)
}
However now the second catch will get called as a result of the throw. So when the someHttpCall failed, after we handled the someHttpCallError error, we would enter this block (fetchUserDetailsError) => { console.log('fetching user error', fetchUserDetailsError) } which is not good since fetchUserDetails never gets called so we shouldn't need to handle fetchUserDetailsError (I know someHttpCallError became fetchUserDetailsError in this case)
I can add some conditional checks in there to distinguish the two errors but it seems less ideal. So I am wondering how I can improve this by using .then and .catch to achieve the same goal here.
I am wondering how I can improve this by using .then and .catch to achieve the same goal here
You don't get to avoid the nesting if you want to replicate the same behaviour:
function fetchUser2() {
return someHttpCall().then(
(user) => {
return fetchUserDetails(user).then(
(details) => {
return displayUserDetails(details)
},
(fetchUserDetailsError) => {
console.log('fetching user error', fetchUserDetailsError)
}
)
},
(someHttpCallError) => {
console.log('networking error:', someHttpCallError)
throw someHttpCallError
}
)
}
(The exact equivalent to try/catch would use .then(…).catch(…) instead of .then(…, …), but you might not actually want that.)
The function I wrote is [nested] which doesn't scale well if the nesting becomes deep and I was trying to rewrite it for better readability […]
For that, I would recommend to combine await with .catch():
async function fetchUser() {
try {
const user = await someHttpCall().catch(someHttpCallError => {
throw new Error('networking error', {cause: someHttpCallError});
});
const details = await fetchUserDetails(user).catch(fetchUserDetailsError => {
throw new Error('fetching user error', {cause: fetchUserDetailsError});
});
return displayUserDetails(details);
} catch (someError) {
console.log(someError.message, someError.cause);
}
}
(The cause option for Error is still quite new, you might need a polyfill for that)
I can add some conditional checks in there to distinguish the two errors but it seems less ideal.
Actually, that sounds like an ideal situation. That means that you don't have to nest any try / catch blocks which could make you code a lot more readable. This is one of the things that async / await is meant to solve.
A solution could be is to create custom errors by extending the Error interface to be able to determine how and where the error occurs.
class CustomError extends Error {
constructor(name, ...args) {
super(...args)
this.name = name
}
}
Throw your errors within the functions that correspond with the error.
async function someHttpCall() {
throw new CustomError('HttpCallError', 'someHttpCall error');
}
async function fetchUserDetails(user) {
throw new CustomError('UserDetailsError', 'fetchUserDetails error')
}
Now you can control your error flow by checking the name property on the error to differentiate your errors.
async function fetchUser() {
try {
const user = await someHttpCall()
const details = await fetchUserDetails(user)
return displayUserDetails(details)
} catch (error) {
switch(error.name) {
case 'HttpCallError':
console.log('Networking error:', error)
break
case 'UserDetailsError':
console.log('Fetching user error', error)
break
}
}
}
I've been inspired by Rust's Result type (which forces you to handle every potential error along the way).
So what I do is handle exceptions in every individual function, and never allow one to throw, instead returning either an Error (if something went wrong) or the desired return value (if no exception occurred). Here's an example of how I do it (comments included):
TS Playground
If you aren't familiar with TypeScript, you can see the JavaScript-only version of the following code (with no type information) at the TypeScript Playground link above (on the right side of the page).
// This is the code in my exception-handling utility module:
// exception-utils.ts
export type Result <T = void, E extends Error = Error> = T | E;
export function getError (value: unknown): Error {
return value instanceof Error ? value : new Error(String(value));
}
export function isError <T>(value: T): value is T & Error {
return value instanceof Error;
}
export function assertNotError <T>(value: T): asserts value is Exclude<T, Error> {
if (value instanceof Error) throw value;
}
// This is how to use it:
// main.ts
import {assertNotError, getError, isError, type Result} from './exception-utils.ts';
/**
* Returns either Error or string ID,
* but won't throw because it catches exceptions internally
*/
declare function getStringFromAPI1 (): Promise<Result<string>>;
/**
* Requires ID from API1. Returns either Error or final number value,
* but won't throw because it catches exceptions internally
*/
declare function getNumberFromAPI2 (id: string): Promise<Result<number>>;
/**
* Create version of second function with no parameter required:
* Returns either Error or final number value,
* but won't throw because it catches exceptions internally
*
* The previous two functions work just like this, using the utilities
*/
async function fetchValueFromAPI2 (): Promise<Result<number>> {
try {
const id = await getStringFromAPI1(); // Error or string
assertNotError(id); // throws if `id` is an Error
return getNumberFromAPI2(id); // Error or number
}
catch (ex) {
return getError(ex);
}
}
async function doSomethingWithValueFromAPI2 (): Promise<void> {
const value = await fetchValueFromAPI2(); // value is number or Error
if (isError(value)) {
// handle error
}
else console.log(value); // value is number at this point
}

Unit test case polling service in Angular

ngOnInit(): void {
this.timeInterval = interval(30000).pipe(startWith(0), switchMap(() => this.deviceService.getDeviceSession())
).subscribe((success: any) => {
this.rowData = success;
console.log(this.rowData)
}, (error: any) => {
this.rowData = [];
if (error.error && error.error.status !== 401) {
this.toastService.error('Error in loading data');
}
}
Test Case
it('should start checking for data after every interval', (done) => {
const dataService = TestBed.get(DeviceService);
// Mock the getStatus function
spyOn(dataService, 'getDeviceSession').and.returnValue(Observable.create().pipe(map(() => 'woo')));
// Should not be initialised yet
expect(component.rowData).toBeUndefined();
setTimeout(()=> {
expect(component.rowData).toBe('woo');
done();
},30000);
});
I am writing this unit test case to check this polling implementation, which is fetching data(array of objects) from service and updating it in the Dom. But the test case is getting failed. I am not sure where i am going wrong.
Getting error rowData.forEach is not a function. Please help how to solve it
Use Jasmin's beforeEach\before to initiate some data before it() instead of doing it in ngOnInit.
https://jasmine.github.io/api/3.5/global
So if im getting right what youre doing is, you initiate the rowData attribute in the ngOnInit life cycle hook. but it's not yet available inside of your it() function.
If you want to run some code and initiate data before you are runing your tests you should use the beforeEach() function and only then it()
check the image bellow:
https://miro.medium.com/max/4800/1*CklcdftSg9EFGsU20ZwdJg.png
A nice guide for doing unit tests with Angular and Jasmine:
https://medium.com/swlh/angular-unit-testing-jasmine-karma-step-by-step-e3376d110ab4

Alternative for `return await …` for the cases when waiting for some result which must be returned

I know that ESLint/TSLint rulest cannot be "right" for 100% of situations. However I need to decide which rules I really don't need.
In ElectonJS, it's not recommended to use Node.js modules in Renderer Process. Instead, Renderer process should send request to Main Process and listen for the response. Below TypeScript class takes care about this routine. (I hope my variable names make code does not need comments, but those are hard to understand, please let me to know in comments)
import { ipcRenderer as IpcRenderer } from "electron";
import InterProcessDataTransferProtocol from "#ProjectInitializer:Root/InterProcessDataTransferProtocol";
import CheckingPathForWriteAccess = InterProcessDataTransferProtocol.CheckingPathForWriteAccess;
import MainProcessEvents = InterProcessDataTransferProtocol.MainProcessEvents;
import Timeout = NodeJS.Timeout;
export default abstract class InterProcessFacilitator {
private static readonly IS_PATH_WRITABLE__RESPONSE_WAITING_PERIOD__MILLISECONDS: number = 10000;
public static async requestCheckingPathForAccessToWrite(targetPath: string): Promise<boolean> {
IpcRenderer.send(
InterProcessDataTransferProtocol.RendererProcessEvents.checkingPathForWriteAccessRequestSent,
{ targetPath }
);
const responseWaitingTimeout: Timeout = setTimeout(
() => { throw new Error("No response from Main Process"); },
InterProcessFacilitator.IS_PATH_WRITABLE__RESPONSE_WAITING_PERIOD__MILLISECONDS
);
return await new Promise<boolean>((resolve: (isWritable: boolean) => void): void => {
IpcRenderer.on(
MainProcessEvents.checkingPathForWriteAccessDone,
(_event: Electron.Event, responsePayload: CheckingPathForWriteAccess.ResponsePayload) =>
{
clearTimeout(responseWaitingTimeout);
if (responsePayload.targetPath === targetPath) {
resolve(responsePayload.isWritable);
}
});
});
}
}
Currently, method requestCheckingPathForAccessToWrite violates no-return-await, the ESLint rules. However it could be used as:
async function checkTheDefaultPathForWrightPermission(): Promise<void> {
try {
const pickedPathIsWritable: boolean = await InterProcessFacilitator
.requestCheckingPathForAccessToWrite(DEFAULT_PATH);
pickedPathIsWritable ?
this.relatedStoreModule.reportAboutUnableToWriteToDirectoryErrorResolution() :
this.relatedStoreModule.reportAboutUnableToWriteToDirectoryErrorOccurrence();
} catch (error) {
console.error(`unable to check wright permission for path ${DEFAULT_PATH}`);
console.error(error);
}
}
From ESLint documentation:
Inside an async function, return await is seldom useful. Since the
return value of an async function is always wrapped in
Promise.resolve, return await doesn’t actually do anything except add
extra time before the overarching Promise resolves or rejects. The
only valid exception is if return await is used in a try/catch
statement to catch errors from another Promise-based function.
Can you criticize either my solution or this ESLint rule, and in first case, suggest the refactoring?

How to use an observable in angular 2 guards' canActivate()

I have created an authentication guard for my angular2 rc5 application.
I am also using a redux store. In that store I keep the user's authentication state.
I read that the guard can return an observable or promise (https://angular.io/docs/ts/latest/guide/router.html#!#guards)
I can't seem to find a way for the guard to wait until the store/observable is updated and only after that update return the guard because the default value of the store will always be false.
First try:
#Injectable()
export class AuthGuard implements CanActivate {
#select(['user', 'authenticated']) authenticated$: Observable<boolean>;
constructor() {}
canActivate(): Promise<boolean> {
return new Promise((resolve, reject) => {
// updated after a while ->
this.authenticated$.subscribe((auth) => {
// will only reach here after the first update of the store
if (auth) { resolve(true); }
// it will always reject because the default value
// is always false and it takes time to update the store
reject(false);
});
});
}
}
Second try:
#Injectable()
export class AuthGuard implements CanActivate {
#select(['user', 'authenticated']) authenticated$: Observable<boolean>;
constructor() {}
canActivate(): Promise<boolean> {
return new Promise((resolve, reject) => {
// tried to convert it for single read since canActivate is called every time. So I actually don't want to subscribe here.
let auth = this.authenticated$.toPromise();
auth.then((authenticated) => {
if (authenticated) { resolve(true); }
reject(false);
});
auth.catch((err) => {
console.log(err);
});
}
}
When you subscribe to an observable, you can provide a callback function; in the example below, I call it CompleteGet. CompleteGet() will only be invoked on a successful get that returns data and not an error. You place whatever follow on logic you need in the callback function.
getCursenByDateTest(){
this.cursenService
.getCursenValueByDateTest("2016-7-30","2016-7-31")
.subscribe(p => {
this.cursens = p;
console.log(p)
console.log(this.cursens.length);
},
error => this.error = error,
() => this.CompleteGet());
}
completeGet() {
// the rest of your logic here - only executes on obtaining result.
}
I believe you can also add a .do() to the observable subscription to accomplish the same thing.
all you need to do is force the observable to update:
canActivate(): Observable<boolean> {
return this.authenticated$.take(1);
}
Edit:
canActivate waits for the source observable to complete, and (most likely, I don't know what happens behind the scenes), the authenticated$ observable emits .next(), not .complete()
From documentation: http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-take
.take(1) method takes first value emitted by the source observable and then completes
Edit2:
I just looked at snippet you pasted, and I was right - the store.select() observable never completes, it always emits .next
Subscribe doesn't return an Observable.
However, you can use the map operator like that:
this.authenticated$.map(
authenticated => {
if(authenticated) {
return true;
}
return false;
}
).first() // or .take(1) to complete on the first event emit

Categories

Resources