Skip to content

Instantly share code, notes, and snippets.

@ghengeveld
Last active November 4, 2019 08:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghengeveld/490a4af9eb33a21dcf314b2b6eb8c7c3 to your computer and use it in GitHub Desktop.
Save ghengeveld/490a4af9eb33a21dcf314b2b6eb8c7c3 to your computer and use it in GitHub Desktop.
TypeScript functions to create mock state objects for React Async
export const mockWaiting = (): AsyncInitial<any> => ({
data: undefined,
error: undefined,
initialValue: undefined,
startedAt: undefined,
finishedAt: undefined,
status: "initial",
isInitial: true,
isPending: false,
isLoading: false,
isFulfilled: false,
isResolved: false,
isRejected: false,
isSettled: false,
counter: 0,
run: () => Promise.resolve(),
reload: () => {},
cancel: () => {},
setError: () => new Error(),
setData: () => {},
});
export const mockPending = <T>(data?: T): AsyncPending<T> => ({
data,
error: undefined,
startedAt: new Date(),
finishedAt: undefined,
status: "pending",
isInitial: false,
isPending: true,
isLoading: true,
isFulfilled: false,
isResolved: false,
isRejected: false,
isSettled: false,
counter: 1,
run: () => Promise.resolve(data as any),
reload: () => {},
cancel: () => {},
setError: () => new Error(),
setData: (d: T) => d,
});
export const mockFulfilled = <T>(data: T): AsyncFulfilled<T> => ({
data,
error: undefined,
startedAt: new Date(),
finishedAt: new Date(),
status: "fulfilled",
isInitial: false,
isPending: false,
isLoading: false,
isFulfilled: true,
isResolved: true,
isRejected: false,
isSettled: true,
counter: 1,
run: () => Promise.resolve(data),
reload: () => {},
cancel: () => {},
setError: () => new Error(),
setData: (d: T) => d,
});
export const mockRejected = (error: Error): AsyncRejected<any> => ({
data: undefined,
error,
startedAt: new Date(),
finishedAt: new Date(),
status: "rejected",
isInitial: false,
isPending: false,
isLoading: false,
isFulfilled: false,
isResolved: false,
isRejected: true,
isSettled: true,
counter: 1,
run: () => Promise.resolve(),
reload: () => {},
cancel: () => {},
setError: () => new Error(),
setData: () => {},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment