简体   繁体   中英

rxjs jest Mocking object in stream

Hi I try to test this code

import { Observable, Subscriber } from 'rxjs';
function getJavaRequest<T>(globals: any): (name: string) => Observable<T> {
return (name: string) => Observable
    .create((observer: Subscriber<T>) => {
        globals[name] = (event: T) => observer.next(event);
    });
    };

I am using jest framework. And I want to create mock object in jest and check that function create stream and add someting to stream And I have something like this

import {getJavaRequest } from './JcefStreams';
import { TestScheduler } from 'rxjs/testing';
test('It should return mocked object from stream', () => {
const testObject = jest.mock();
let test;
getJavaRequest(testObject).subscribe(e: any => e == test);

expect(test).toBe(global);
});

But it not working correctly

You'll need to create a mocked observable.

For example:

//...
import { of } from 'rxjs/observable/of';

class RequestServiceMock {
  get = jest.fn();
}

describe('', () => {
  it('', () => {
    const requestService = RequestService as RequestServiceMock;
    requestService.get.mockReturnValue(of([]));

    requestService.get().subscribe(_ => expect(_).toBeTruthy())
  });
});

Hopefully this helps.

Sollution based on https://blog.jiayihu.net/testing-observables-in-rxjs6/

 describe('Check that getJavaRequest create observable with event', () => { let scheduler: TestScheduler; beforeEach(() => { scheduler = new TestScheduler(assertDeepEqual); }); test('', () => { let testObject: {[name: string]: ((event: string) => void)} = {}; const subscriber = jest.fn(); const stremUnderTests = getJavaRequest<string>(testObject)('testStream').subscribe(subscriber); testObject.testStream('a'); testObject.testStream('b'); expect(subscriber).toHaveBeenCalledWith('a') expect(subscriber).toHaveBeenCalledWith('b') expect(subscriber).toHaveBeenCalledTimes(2) }); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM