Skip to content

Commit

Permalink
feat(rx-stateful): add testing utils for rxRequest
Browse files Browse the repository at this point in the history
close #7
  • Loading branch information
michaelbe812 committed Dec 1, 2024
1 parent 4dd7ea2 commit db89be4
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 0 deletions.
1 change: 1 addition & 0 deletions libs/rx-stateful/testing/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export {mockRxStateful, RxStatefulMock} from './lib/mock-rx-stateful$'
export {mockRxRequest, RxRequestMock} from './lib/mock-rx-request'
41 changes: 41 additions & 0 deletions libs/rx-stateful/testing/src/lib/mock-rx-request.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { mockRxRequest } from "./mock-rx-request";
import { subscribeSpyTo } from "@hirez_io/observer-spy";

describe('mockRxRequest', () => {
it('should create mock with all properties defined', () => {
const mock = mockRxRequest();

expect(mock.instance).toBeTruthy();
expect(mock.instance.value$).toBeTruthy();
expect(mock.instance.refresh).toBeTruthy();
expect(mock.state$Trigger).toBeTruthy();
expect(mock.refreshTrigger).toBeTruthy();
});

describe('state$Trigger', () => {
it('should emit when trigger emits', () => {
const mock = mockRxRequest<string>();

const result = subscribeSpyTo(mock.instance.value$());
mock.state$Trigger.next({ isSuspense: true });
mock.state$Trigger.next({ value: 'test', isSuspense: false });

expect(result.getValues()).toEqual([
{ isSuspense: true },
{ value: 'test', isSuspense: false }
]);
});
});

describe('refresh', () => {
it('should emit when refresh is called', () => {
const mock = mockRxRequest<string>();
const refreshSpy = jest.fn();

mock.refreshTrigger.subscribe(refreshSpy);
mock.instance.refresh();

expect(refreshSpy).toHaveBeenCalled();
});
});
});
29 changes: 29 additions & 0 deletions libs/rx-stateful/testing/src/lib/mock-rx-request.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { RxStateful, RxRequest } from '@angular-kit/rx-stateful';
import { BehaviorSubject, Observable, ReplaySubject, Subject } from "rxjs";

export interface RxRequestMock<T, E = unknown> {
instance: RxRequest<T, E>;
state$Trigger: Subject<Partial<RxStateful<T, E>>>;
refreshTrigger: Subject<void>;
}

export function mockRxRequest<T, E = unknown>(): RxRequestMock<T, E> {
function createTrigger<T>(startValue?: T | null | undefined) {
const trigger = startValue ? new BehaviorSubject(startValue) : new ReplaySubject<T>(1);
return trigger;
}

const state$Trigger = createTrigger<Partial<RxStateful<T, E>>>();
const refreshTrigger = new Subject<void>();

const instance: RxRequest<T, E> = {
value$: () => state$Trigger.asObservable() as Observable<RxStateful<T, E>>,
refresh: () => refreshTrigger.next()
};

return {
instance,
state$Trigger,
refreshTrigger
};
}

0 comments on commit db89be4

Please sign in to comment.