Store refactor: make it easier to test stores (#9290)
* refactor: convert RoomViewStore from flux Store to standard EventEmitter Parts of a series of experimental changes to improve the design of stores. * Use a gen5 store for RoomViewStore for now due to lock handling * Revert "Use a gen5 store for RoomViewStore for now due to lock handling" This reverts commit 1076af071d997d87b8ae0b0dcddfd1ae428665af. * Add untilEmission and tweak untilDispatch; use it in RoomViewStore * Add more RVS tests; remove custom room ID listener code and use EventEmitter * Better comments * Null guard `dis` as tests mock out `defaultDispatcher` * Additional tests
This commit is contained in:
parent
1f1a18f914
commit
06c4ba32cd
11 changed files with 289 additions and 129 deletions
|
@ -42,6 +42,7 @@ import { RightPanelPhases } from "../../../src/stores/right-panel/RightPanelStor
|
|||
import { LocalRoom, LocalRoomState } from "../../../src/models/LocalRoom";
|
||||
import { DirectoryMember } from "../../../src/utils/direct-messages";
|
||||
import { createDmLocalRoom } from "../../../src/utils/dm/createDmLocalRoom";
|
||||
import { UPDATE_EVENT } from "../../../src/stores/AsyncStore";
|
||||
|
||||
const RoomView = wrapInMatrixClientContext(_RoomView);
|
||||
|
||||
|
@ -74,12 +75,13 @@ describe("RoomView", () => {
|
|||
const mountRoomView = async (): Promise<ReactWrapper> => {
|
||||
if (RoomViewStore.instance.getRoomId() !== room.roomId) {
|
||||
const switchedRoom = new Promise<void>(resolve => {
|
||||
const subscription = RoomViewStore.instance.addListener(() => {
|
||||
const subFn = () => {
|
||||
if (RoomViewStore.instance.getRoomId()) {
|
||||
subscription.remove();
|
||||
RoomViewStore.instance.off(UPDATE_EVENT, subFn);
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
};
|
||||
RoomViewStore.instance.on(UPDATE_EVENT, subFn);
|
||||
});
|
||||
|
||||
defaultDispatcher.dispatch<ViewRoomPayload>({
|
||||
|
|
|
@ -18,13 +18,13 @@ import { Room } from 'matrix-js-sdk/src/matrix';
|
|||
|
||||
import { RoomViewStore } from '../../src/stores/RoomViewStore';
|
||||
import { Action } from '../../src/dispatcher/actions';
|
||||
import * as testUtils from '../test-utils';
|
||||
import { flushPromises, getMockClientWithEventEmitter } from '../test-utils';
|
||||
import { getMockClientWithEventEmitter, untilDispatch, untilEmission } from '../test-utils';
|
||||
import SettingsStore from '../../src/settings/SettingsStore';
|
||||
import { SlidingSyncManager } from '../../src/SlidingSyncManager';
|
||||
import { TimelineRenderingType } from '../../src/contexts/RoomContext';
|
||||
|
||||
const dispatch = testUtils.getDispatchForStore(RoomViewStore.instance);
|
||||
import { MatrixDispatcher } from '../../src/dispatcher/dispatcher';
|
||||
import { UPDATE_EVENT } from '../../src/stores/AsyncStore';
|
||||
import { ActiveRoomChangedPayload } from '../../src/dispatcher/payloads/ActiveRoomChangedPayload';
|
||||
|
||||
jest.mock('../../src/utils/DMRoomMap', () => {
|
||||
const mock = {
|
||||
|
@ -40,13 +40,18 @@ jest.mock('../../src/utils/DMRoomMap', () => {
|
|||
|
||||
describe('RoomViewStore', function() {
|
||||
const userId = '@alice:server';
|
||||
const roomId = "!randomcharacters:aser.ver";
|
||||
// we need to change the alias to ensure cache misses as the cache exists
|
||||
// through all tests.
|
||||
let alias = "#somealias2:aser.ver";
|
||||
const mockClient = getMockClientWithEventEmitter({
|
||||
joinRoom: jest.fn(),
|
||||
getRoom: jest.fn(),
|
||||
getRoomIdForAlias: jest.fn(),
|
||||
isGuest: jest.fn(),
|
||||
});
|
||||
const room = new Room('!room:server', mockClient, userId);
|
||||
const room = new Room(roomId, mockClient, userId);
|
||||
let dis: MatrixDispatcher;
|
||||
|
||||
beforeEach(function() {
|
||||
jest.clearAllMocks();
|
||||
|
@ -56,54 +61,131 @@ describe('RoomViewStore', function() {
|
|||
mockClient.isGuest.mockReturnValue(false);
|
||||
|
||||
// Reset the state of the store
|
||||
dis = new MatrixDispatcher();
|
||||
RoomViewStore.instance.reset();
|
||||
RoomViewStore.instance.resetDispatcher(dis);
|
||||
});
|
||||
|
||||
it('can be used to view a room by ID and join', async () => {
|
||||
dispatch({ action: Action.ViewRoom, room_id: '!randomcharacters:aser.ver' });
|
||||
dispatch({ action: Action.JoinRoom });
|
||||
await flushPromises();
|
||||
expect(mockClient.joinRoom).toHaveBeenCalledWith('!randomcharacters:aser.ver', { viaServers: [] });
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: roomId });
|
||||
dis.dispatch({ action: Action.JoinRoom });
|
||||
await untilDispatch(Action.JoinRoomReady, dis);
|
||||
expect(mockClient.joinRoom).toHaveBeenCalledWith(roomId, { viaServers: [] });
|
||||
expect(RoomViewStore.instance.isJoining()).toBe(true);
|
||||
});
|
||||
|
||||
it('can auto-join a room', async () => {
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: roomId, auto_join: true });
|
||||
await untilDispatch(Action.JoinRoomReady, dis);
|
||||
expect(mockClient.joinRoom).toHaveBeenCalledWith(roomId, { viaServers: [] });
|
||||
expect(RoomViewStore.instance.isJoining()).toBe(true);
|
||||
});
|
||||
|
||||
it('emits ActiveRoomChanged when the viewed room changes', async () => {
|
||||
const roomId2 = "!roomid:2";
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: roomId });
|
||||
let payload = await untilDispatch(Action.ActiveRoomChanged, dis) as ActiveRoomChangedPayload;
|
||||
expect(payload.newRoomId).toEqual(roomId);
|
||||
expect(payload.oldRoomId).toEqual(null);
|
||||
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: roomId2 });
|
||||
payload = await untilDispatch(Action.ActiveRoomChanged, dis) as ActiveRoomChangedPayload;
|
||||
expect(payload.newRoomId).toEqual(roomId2);
|
||||
expect(payload.oldRoomId).toEqual(roomId);
|
||||
});
|
||||
|
||||
it('invokes room activity listeners when the viewed room changes', async () => {
|
||||
const roomId2 = "!roomid:2";
|
||||
const callback = jest.fn();
|
||||
RoomViewStore.instance.addRoomListener(roomId, callback);
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: roomId });
|
||||
await untilDispatch(Action.ActiveRoomChanged, dis) as ActiveRoomChangedPayload;
|
||||
expect(callback).toHaveBeenCalledWith(true);
|
||||
expect(callback).not.toHaveBeenCalledWith(false);
|
||||
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: roomId2 });
|
||||
await untilDispatch(Action.ActiveRoomChanged, dis) as ActiveRoomChangedPayload;
|
||||
expect(callback).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it('can be used to view a room by alias and join', async () => {
|
||||
const roomId = "!randomcharacters:aser.ver";
|
||||
const alias = "#somealias2:aser.ver";
|
||||
|
||||
mockClient.getRoomIdForAlias.mockResolvedValue({ room_id: roomId, servers: [] });
|
||||
|
||||
dispatch({ action: Action.ViewRoom, room_alias: alias });
|
||||
await flushPromises();
|
||||
await flushPromises();
|
||||
dis.dispatch({ action: Action.ViewRoom, room_alias: alias });
|
||||
await untilDispatch((p) => { // wait for the re-dispatch with the room ID
|
||||
return p.action === Action.ViewRoom && p.room_id === roomId;
|
||||
}, dis);
|
||||
|
||||
// roomId is set to id of the room alias
|
||||
expect(RoomViewStore.instance.getRoomId()).toBe(roomId);
|
||||
|
||||
// join the room
|
||||
dispatch({ action: Action.JoinRoom });
|
||||
dis.dispatch({ action: Action.JoinRoom }, true);
|
||||
|
||||
await untilDispatch(Action.JoinRoomReady, dis);
|
||||
|
||||
expect(RoomViewStore.instance.isJoining()).toBeTruthy();
|
||||
await flushPromises();
|
||||
|
||||
expect(mockClient.joinRoom).toHaveBeenCalledWith(alias, { viaServers: [] });
|
||||
});
|
||||
|
||||
it('emits ViewRoomError if the alias lookup fails', async () => {
|
||||
alias = "#something-different:to-ensure-cache-miss";
|
||||
mockClient.getRoomIdForAlias.mockRejectedValue(new Error("network error or something"));
|
||||
dis.dispatch({ action: Action.ViewRoom, room_alias: alias });
|
||||
const payload = await untilDispatch(Action.ViewRoomError, dis);
|
||||
expect(payload.room_id).toBeNull();
|
||||
expect(payload.room_alias).toEqual(alias);
|
||||
expect(RoomViewStore.instance.getRoomAlias()).toEqual(alias);
|
||||
});
|
||||
|
||||
it('emits JoinRoomError if joining the room fails', async () => {
|
||||
const joinErr = new Error("network error or something");
|
||||
mockClient.joinRoom.mockRejectedValue(joinErr);
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: roomId });
|
||||
dis.dispatch({ action: Action.JoinRoom });
|
||||
await untilDispatch(Action.JoinRoomError, dis);
|
||||
expect(RoomViewStore.instance.isJoining()).toBe(false);
|
||||
expect(RoomViewStore.instance.getJoinError()).toEqual(joinErr);
|
||||
});
|
||||
|
||||
it('remembers the event being replied to when swapping rooms', async () => {
|
||||
dispatch({ action: Action.ViewRoom, room_id: '!randomcharacters:aser.ver' });
|
||||
await flushPromises();
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: roomId });
|
||||
await untilDispatch(Action.ActiveRoomChanged, dis);
|
||||
const replyToEvent = {
|
||||
getRoomId: () => '!randomcharacters:aser.ver',
|
||||
getRoomId: () => roomId,
|
||||
};
|
||||
dispatch({ action: 'reply_to_event', event: replyToEvent, context: TimelineRenderingType.Room });
|
||||
await flushPromises();
|
||||
dis.dispatch({ action: 'reply_to_event', event: replyToEvent, context: TimelineRenderingType.Room });
|
||||
await untilEmission(RoomViewStore.instance, UPDATE_EVENT);
|
||||
expect(RoomViewStore.instance.getQuotingEvent()).toEqual(replyToEvent);
|
||||
// view the same room, should remember the event.
|
||||
dispatch({ action: Action.ViewRoom, room_id: '!randomcharacters:aser.ver' });
|
||||
await flushPromises();
|
||||
// set the highlighed flag to make sure there is a state change so we get an update event
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: roomId, highlighted: true });
|
||||
await untilEmission(RoomViewStore.instance, UPDATE_EVENT);
|
||||
expect(RoomViewStore.instance.getQuotingEvent()).toEqual(replyToEvent);
|
||||
});
|
||||
|
||||
it('swaps to the replied event room if it is not the current room', async () => {
|
||||
const roomId2 = "!room2:bar";
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: roomId });
|
||||
await untilDispatch(Action.ActiveRoomChanged, dis);
|
||||
const replyToEvent = {
|
||||
getRoomId: () => roomId2,
|
||||
};
|
||||
dis.dispatch({ action: 'reply_to_event', event: replyToEvent, context: TimelineRenderingType.Room });
|
||||
await untilDispatch(Action.ViewRoom, dis);
|
||||
expect(RoomViewStore.instance.getQuotingEvent()).toEqual(replyToEvent);
|
||||
expect(RoomViewStore.instance.getRoomId()).toEqual(roomId2);
|
||||
});
|
||||
|
||||
it('removes the roomId on ViewHomePage', async () => {
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: roomId });
|
||||
await untilDispatch(Action.ActiveRoomChanged, dis);
|
||||
expect(RoomViewStore.instance.getRoomId()).toEqual(roomId);
|
||||
|
||||
dis.dispatch({ action: Action.ViewHomePage });
|
||||
await untilEmission(RoomViewStore.instance, UPDATE_EVENT);
|
||||
expect(RoomViewStore.instance.getRoomId()).toBeNull();
|
||||
});
|
||||
|
||||
describe('Sliding Sync', function() {
|
||||
beforeEach(() => {
|
||||
jest.spyOn(SettingsStore, 'getValue').mockImplementation((settingName, roomId, value) => {
|
||||
|
@ -117,9 +199,8 @@ describe('RoomViewStore', function() {
|
|||
Promise.resolve(""),
|
||||
);
|
||||
const subscribedRoomId = "!sub1:localhost";
|
||||
dispatch({ action: Action.ViewRoom, room_id: subscribedRoomId });
|
||||
await flushPromises();
|
||||
await flushPromises();
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: subscribedRoomId });
|
||||
await untilDispatch(Action.ActiveRoomChanged, dis);
|
||||
expect(RoomViewStore.instance.getRoomId()).toBe(subscribedRoomId);
|
||||
expect(setRoomVisible).toHaveBeenCalledWith(subscribedRoomId, true);
|
||||
});
|
||||
|
@ -129,20 +210,27 @@ describe('RoomViewStore', function() {
|
|||
const setRoomVisible = jest.spyOn(SlidingSyncManager.instance, "setRoomVisible").mockReturnValue(
|
||||
Promise.resolve(""),
|
||||
);
|
||||
const subscribedRoomId = "!sub2:localhost";
|
||||
const subscribedRoomId2 = "!sub3:localhost";
|
||||
dispatch({ action: Action.ViewRoom, room_id: subscribedRoomId });
|
||||
dispatch({ action: Action.ViewRoom, room_id: subscribedRoomId2 });
|
||||
// sub(1) then unsub(1) sub(2)
|
||||
expect(setRoomVisible).toHaveBeenCalledTimes(3);
|
||||
await flushPromises();
|
||||
await flushPromises();
|
||||
// this should not churn, extra call to allow unsub(1)
|
||||
expect(setRoomVisible).toHaveBeenCalledTimes(4);
|
||||
// flush a bit more to ensure this doesn't change
|
||||
await flushPromises();
|
||||
await flushPromises();
|
||||
expect(setRoomVisible).toHaveBeenCalledTimes(4);
|
||||
const subscribedRoomId = "!sub1:localhost";
|
||||
const subscribedRoomId2 = "!sub2:localhost";
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: subscribedRoomId }, true);
|
||||
dis.dispatch({ action: Action.ViewRoom, room_id: subscribedRoomId2 }, true);
|
||||
await untilDispatch(Action.ActiveRoomChanged, dis);
|
||||
// sub(1) then unsub(1) sub(2), unsub(1)
|
||||
const wantCalls = [
|
||||
[subscribedRoomId, true],
|
||||
[subscribedRoomId, false],
|
||||
[subscribedRoomId2, true],
|
||||
[subscribedRoomId, false],
|
||||
];
|
||||
expect(setRoomVisible).toHaveBeenCalledTimes(wantCalls.length);
|
||||
wantCalls.forEach((v, i) => {
|
||||
try {
|
||||
expect(setRoomVisible.mock.calls[i][0]).toEqual(v[0]);
|
||||
expect(setRoomVisible.mock.calls[i][1]).toEqual(v[1]);
|
||||
} catch (err) {
|
||||
throw new Error(`i=${i} got ${setRoomVisible.mock.calls[i]} want ${v}`);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
@ -35,7 +35,6 @@ import { normalize } from "matrix-js-sdk/src/utils";
|
|||
import { ReEmitter } from "matrix-js-sdk/src/ReEmitter";
|
||||
|
||||
import { MatrixClientPeg as peg } from '../../src/MatrixClientPeg';
|
||||
import dis from '../../src/dispatcher/dispatcher';
|
||||
import { makeType } from "../../src/utils/TypeUtils";
|
||||
import { ValidatedServerConfig } from "../../src/utils/ValidatedServerConfig";
|
||||
import { EnhancedMap } from "../../src/utils/maps";
|
||||
|
@ -456,18 +455,6 @@ export function mkServerConfig(hsUrl, isUrl) {
|
|||
});
|
||||
}
|
||||
|
||||
export function getDispatchForStore(store) {
|
||||
// Mock the dispatcher by gut-wrenching. Stores can only __emitChange whilst a
|
||||
// dispatcher `_isDispatching` is true.
|
||||
return (payload) => {
|
||||
// these are private properties in flux dispatcher
|
||||
// fool ts
|
||||
(dis as any)._isDispatching = true;
|
||||
(dis as any)._callbacks[store._dispatchToken](payload);
|
||||
(dis as any)._isDispatching = false;
|
||||
};
|
||||
}
|
||||
|
||||
// These methods make some use of some private methods on the AsyncStoreWithClient to simplify getting into a consistent
|
||||
// ready state without needing to wire up a dispatcher and pretend to be a js-sdk client.
|
||||
|
||||
|
|
|
@ -24,18 +24,104 @@ import { DispatcherAction } from "../../src/dispatcher/actions";
|
|||
|
||||
export const emitPromise = (e: EventEmitter, k: string | symbol) => new Promise(r => e.once(k, r));
|
||||
|
||||
export function untilDispatch(waitForAction: DispatcherAction): Promise<ActionPayload> {
|
||||
let dispatchHandle: string;
|
||||
return new Promise<ActionPayload>(resolve => {
|
||||
dispatchHandle = defaultDispatcher.register(payload => {
|
||||
if (payload.action === waitForAction) {
|
||||
defaultDispatcher.unregister(dispatchHandle);
|
||||
resolve(payload);
|
||||
/**
|
||||
* Waits for a certain payload to be dispatched.
|
||||
* @param waitForAction The action string to wait for or the callback which is invoked for every dispatch. If this returns true, stops waiting.
|
||||
* @param timeout The max time to wait before giving up and stop waiting. If 0, no timeout.
|
||||
* @param dispatcher The dispatcher to listen on.
|
||||
* @returns A promise which resolves when the callback returns true. Resolves with the payload that made it stop waiting.
|
||||
* Rejects when the timeout is reached.
|
||||
*/
|
||||
export function untilDispatch(
|
||||
waitForAction: DispatcherAction | ((payload: ActionPayload) => boolean), dispatcher=defaultDispatcher, timeout=1000,
|
||||
): Promise<ActionPayload> {
|
||||
const callerLine = new Error().stack.toString().split("\n")[2];
|
||||
if (typeof waitForAction === "string") {
|
||||
const action = waitForAction;
|
||||
waitForAction = (payload) => {
|
||||
return payload.action === action;
|
||||
};
|
||||
}
|
||||
const callback = waitForAction as ((payload: ActionPayload) => boolean);
|
||||
return new Promise((resolve, reject) => {
|
||||
let fulfilled = false;
|
||||
let timeoutId;
|
||||
// set a timeout handler if needed
|
||||
if (timeout > 0) {
|
||||
timeoutId = setTimeout(() => {
|
||||
if (!fulfilled) {
|
||||
reject(new Error(`untilDispatch: timed out at ${callerLine}`));
|
||||
fulfilled = true;
|
||||
}
|
||||
}, timeout);
|
||||
}
|
||||
// listen for dispatches
|
||||
const token = dispatcher.register((p: ActionPayload) => {
|
||||
const finishWaiting = callback(p);
|
||||
if (finishWaiting || fulfilled) { // wait until we're told or we timeout
|
||||
// if we haven't timed out, resolve now with the payload.
|
||||
if (!fulfilled) {
|
||||
resolve(p);
|
||||
fulfilled = true;
|
||||
}
|
||||
// cleanup
|
||||
dispatcher.unregister(token);
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits for a certain event to be emitted.
|
||||
* @param emitter The EventEmitter to listen on.
|
||||
* @param eventName The event string to wait for.
|
||||
* @param check Optional function which is invoked when the event fires. If this returns true, stops waiting.
|
||||
* @param timeout The max time to wait before giving up and stop waiting. If 0, no timeout.
|
||||
* @returns A promise which resolves when the callback returns true or when the event is emitted if
|
||||
* no callback is provided. Rejects when the timeout is reached.
|
||||
*/
|
||||
export function untilEmission(
|
||||
emitter: EventEmitter, eventName: string, check: ((...args: any[]) => boolean)=undefined, timeout=1000,
|
||||
): Promise<void> {
|
||||
const callerLine = new Error().stack.toString().split("\n")[2];
|
||||
return new Promise((resolve, reject) => {
|
||||
let fulfilled = false;
|
||||
let timeoutId;
|
||||
// set a timeout handler if needed
|
||||
if (timeout > 0) {
|
||||
timeoutId = setTimeout(() => {
|
||||
if (!fulfilled) {
|
||||
reject(new Error(`untilEmission: timed out at ${callerLine}`));
|
||||
fulfilled = true;
|
||||
}
|
||||
}, timeout);
|
||||
}
|
||||
const callback = (...args: any[]) => {
|
||||
// if they supplied a check function, call it now. Bail if it returns false.
|
||||
if (check) {
|
||||
if (!check(...args)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// we didn't time out, resolve. Otherwise, we already rejected so don't resolve now.
|
||||
if (!fulfilled) {
|
||||
resolve();
|
||||
fulfilled = true;
|
||||
}
|
||||
// cleanup
|
||||
emitter.off(eventName, callback);
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
};
|
||||
// listen for emissions
|
||||
emitter.on(eventName, callback);
|
||||
});
|
||||
}
|
||||
|
||||
export const findByAttr = (attr: string) => (component: ReactWrapper, value: string) =>
|
||||
component.find(`[${attr}="${value}"]`);
|
||||
export const findByTestId = findByAttr('data-test-id');
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue