context-state: fix route-state broken tests

This commit is contained in:
Josep M Sobrepere 2022-10-18 11:48:23 +02:00
parent 1254951e7e
commit ad249a2769
No known key found for this signature in database
GPG Key ID: 9A207FDA2481C91A
3 changed files with 29 additions and 4 deletions

View File

@ -106,7 +106,9 @@ export const detachedNode = <T>(
if (isParentLoaded) {
// an actual change of context
const hasPreviousValue = instance && instance.currentValue !== EMPTY_VALUE
let previousValue = instance ? instance.currentValue : EMPTY_VALUE
const hasPreviousValue = previousValue !== EMPTY_VALUE
if (!instance) {
instance = {
subject: new ReplaySubject<T>(1),
@ -154,7 +156,10 @@ export const detachedNode = <T>(
actualInstance.subscription =
observable?.subscribe({
next(value) {
let prevValue = actualInstance.currentValue
let prevValue =
previousValue !== EMPTY_VALUE
? previousValue
: actualInstance.currentValue
actualInstance.currentValue = value
const prevPromise = actualInstance.promise
actualInstance.promise = null
@ -186,6 +191,8 @@ export const detachedNode = <T>(
runChildren(key, true, false)
prevSubect?.complete()
}
previousValue = EMPTY_VALUE
return
}

View File

@ -40,7 +40,9 @@ describe("routeState", () => {
)
root.run()
expect(() => key.getValue()).toThrow() // TODO which error?
expect(() => key.getValue()).toThrow(
'Invalid Route. Received "c" while valid keys are: "a, b"',
)
})
it("errors if the selector throws an error", () => {

View File

@ -10,6 +10,17 @@ import { of } from "rxjs"
import { substate } from "./substate"
import { StateNode, Ctx } from "./types"
export class InvalidRouteError extends Error {
constructor(key: string, keys: string[]) {
super(
`Invalid Route. Received "${key}" while valid keys are: "${keys.join(
", ",
)}"`,
)
this.name = "InvalidRouteError"
}
}
export const routeState = <
T,
O extends { [P in keyof any]: ((value: T) => any) | null },
@ -25,7 +36,12 @@ export const routeState = <
routes: O,
selector: (value: T, ctx: Ctx) => keyof O,
): [StateNode<keyof O>, OT] => {
const keyState = substate(parent, (ctx) => of(selector(ctx(parent), ctx)))
const keys = new Set(Object.keys(routes))
const keyState = substate(parent, (ctx) => {
const key = selector(ctx(parent), ctx) as string
if (!keys.has(key)) throw new InvalidRouteError(key, [...keys])
return of(key)
})
const routedState = mapRecord(routes, (mapper) => {
const result = detachedNode<any>((ctx) => {