Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upgrade to Angular/rxjs 6 breaks Karma test

After I upgraded to new version of Angular, one of my tests that previously worked broke, and I don't know why. Namely I have a function to log errors:

import { Observable, of } from 'rxjs';

export function handleError<T>(operation='operation', result?: T) {
  return (error: any): Observable<T> => {
    console.error(error);
    console.info(`${operation} failed: ${error.message}`);
    return of(result as T);
  }
}

And I test it with:

it('#handleError return function should return an object', () => {
  let errorFunction = handleError('dummyFetch', [{}]);
  expect(typeof errorFunction({ message: 'Something went wrong.'})).toEqual('object');
  expect(errorFunction({ message: 'Something went wrong.'})).toEqual(of([{}]));
});

The line that fails is expect(errorFunction({ message: 'Something went wrong.'})).toEqual(of([{}])); and the error reported: Expected $._subscribe = Function to equal Function.. Could it be that test is failing because of the asynchronous error function?

Edit: This is the solution I settled with:

it('#handleError return function should return an object', () => {
  let errorFunction = handleError('dummyFetch', [{}]);
  expect(typeof errorFunction({ message: 'Something went wrong.' })).toEqual('object');

  let error = errorFunction({ message: 'Something went wrong.' });
  error.subscribe(value => {
    expect(value).toEqual([{}]);
  });
});
like image 236
Gitnik Avatar asked May 21 '18 08:05

Gitnik


1 Answers

If you rewrite your test as

it('#handleError return function should return an object', () => {
  let errorFunction = handleError('dummyFetch', [{}]);
  expect(typeof errorFunction({ message: 'Something went wrong.'})).toEqual('object');
  errorFunction.subscribe((result) => {
        expect(result).toEqual([{}]);
    });
});

This test failed due to observables and the subscription in your final expect should fix this.

like image 163
Andrew Fraser Avatar answered Oct 05 '22 02:10

Andrew Fraser