Home Reference Source

src/groups/GroupRepository.spec.ts

import {WapiClient} from '@quobis/wapi-client';
import {expect} from 'chai';
import {TestScheduler} from 'rxjs/testing';
import sinon, {StubbedInstance, stubConstructor} from 'ts-sinon';

import {WacRequest} from '../wac-proxy/wac-stack/WacRequest';
import {GroupService} from '../wac-proxy/wac-stack/groups/GroupService';
import {GroupDtoBuilder, GroupEventDtoBuilder} from '../wac-proxy/wac-stack/groups/builders';
import {GroupDto} from '../wac-proxy/wac-stack/groups/types';

import {Group} from './Group';
import {GroupRepository} from './GroupRepository';

const createGroupModel = (...dtos: GroupDto[]): Group[] => dtos.map(dto => Group.of({
	id: dto.groupId,
	name: dto.name,
	owner: dto.owner.id,
	participants: dto.participants,
}));

describe('groups/groupRepository', () => {
	let testScheduler: TestScheduler;
	let groupService: StubbedInstance<GroupService>;

	beforeEach(() => {
		testScheduler = new TestScheduler((actual, expected) => {
			expect(actual).to.deep.equal(expected);
		});
		const wacRequest = stubConstructor(WacRequest, stubConstructor(WapiClient));
		groupService = stubConstructor(GroupService, wacRequest);
	});

	afterEach(() => {
		sinon.restore();
	});

	it('should be lazily created', () => {
		groupService.fetch.resolves([]);
		new GroupRepository(groupService);
		sinon.assert.notCalled(groupService.fetch);
	});

	it('should resolve groups and react to events', () => {
		testScheduler.run(({expectObservable, cold, hot}) => {
			const group1Dto = GroupDtoBuilder.of().build();
			const group2Dto = GroupDtoBuilder.of().build();
			const group1UpdatedDto = {...group1Dto, participants: ['alice']};

			groupService.fetch.returns(cold('a|', {a: [group1Dto]}));
			sinon.stub(groupService, 'event$').value(hot('^ 499ms a 99ms b 99ms c', {
				a: GroupEventDtoBuilder.of().withMethod('POST').withBody(group2Dto).build(),
				b: GroupEventDtoBuilder.of().withMethod('PUT').withBody(group1UpdatedDto).build(),
				c: GroupEventDtoBuilder.of().withMethod('DELETE').withBody(group1Dto).build(),
			}));

			const groupRepository = new GroupRepository(groupService);

			expectObservable(groupRepository.groups$).toBe('a 499ms b 99ms c 99ms d', {
				a: createGroupModel(group1Dto),
				b: createGroupModel(group1Dto, group2Dto),
				c: createGroupModel(group1UpdatedDto, group2Dto),
				d: createGroupModel(group2Dto),
			});
		});
	});
});