First commit

...featuring almost complete rewrite. Frustration is a powerful force 😅
This commit is contained in:
Johan Öbrink 2021-02-06 20:15:33 +01:00
commit d623705563
29 changed files with 7810 additions and 0 deletions

3
.eslintrc.js Normal file
View File

@ -0,0 +1,3 @@
module.exports = {
extends: ['airbnb-typescript'],
}

106
.gitignore vendored Normal file
View File

@ -0,0 +1,106 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# Next.js build output
.next
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
record

7
babel.config.js Normal file
View File

@ -0,0 +1,7 @@
module.exports = {
presets: [
'@babel/preset-env',
'@babel/preset-react',
'@babel/preset-typescript',
],
}

13
jest.config.js Normal file
View File

@ -0,0 +1,13 @@
module.exports = {
// Automatically clear mock calls and instances between every test
clearMocks: true,
// The directory where Jest should output its coverage files
coverageDirectory: 'coverage',
// Indicates which provider should be used to instrument code for coverage
coverageProvider: 'v8',
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: ['<rootDir>/jest.setup.js'],
// The test environment that will be used for testing
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
}

1
jest.setup.js Normal file
View File

@ -0,0 +1 @@
import 'regenerator-runtime/runtime'

46
package.json Normal file
View File

@ -0,0 +1,46 @@
{
"name": "@skolplattformen/api-hooks",
"version": "0.0.0",
"main": "dist/",
"author": "Johan Öbrink <johan.obrink@gmail.com>",
"license": "Apache-2.0",
"private": false,
"scripts": {
"lint": "eslint 'src/**/*.ts' --quiet --fix",
"test": "jest",
"build": "tsc",
"prepare": "yarn build",
"publish-package": "npm publish --access public"
},
"dependencies": {
"@skolplattformen/embedded-api": "^0.20.0",
"react": "^16.11.0",
"react-redux": "^7.2.2",
"redux": "^4.0.5"
},
"devDependencies": {
"@babel/preset-env": "^7.12.13",
"@babel/preset-react": "^7.12.13",
"@babel/preset-typescript": "^7.12.13",
"@testing-library/jest-dom": "^5.11.9",
"@testing-library/react": "^11.2.5",
"@testing-library/react-hooks": "^5.0.3",
"@types/jest": "^26.0.20",
"@types/react": "^16.14.3",
"@types/react-redux": "^7.1.16",
"@typescript-eslint/eslint-plugin": "^4.4.1",
"babel-jest": "^26.6.3",
"eslint": "^7.19.0",
"eslint-config-airbnb-typescript": "^12.0.0",
"eslint-plugin-import": "^2.22.0",
"eslint-plugin-jsx-a11y": "^6.3.1",
"eslint-plugin-react": "^7.20.3",
"eslint-plugin-react-hooks": "^4.0.8",
"events": "^3.2.0",
"jest": "^26.6.3",
"react-dom": "^16.11.0",
"react-test-renderer": "^16.11.0",
"regenerator-runtime": "^0.13.7",
"typescript": "^3.9.7"
}
}

View File

@ -0,0 +1,27 @@
import { EventEmitter } from 'events'
const emitter = new EventEmitter()
const createApi = () => ({
emitter,
isLoggedIn: false,
login: jest.fn(),
logout: jest.fn(),
on: jest.fn().mockImplementation((...args) => emitter.on(...args)),
off: jest.fn().mockImplementation((...args) => emitter.off(...args)),
getSessionCookie: jest.fn(),
getPersonalNumber: jest.fn(),
getCalendar: jest.fn(),
getChildren: jest.fn(),
getClassmates: jest.fn(),
getMenu: jest.fn(),
getNews: jest.fn(),
getNotifications: jest.fn(),
getSchedule: jest.fn(),
getUser: jest.fn(),
})
const init = jest.fn().mockImplementation(() => createApi())
export default init

View File

@ -0,0 +1,17 @@
const pause = (ms = 0) => new Promise((r) => setTimeout(r, ms))
export default (init = {}, delay = 0) => {
const cache = {}
Object.keys(init).forEach((key) => {
cache[key] = JSON.stringify(init[key])
})
const getItem = async (key) => {
await pause(delay)
return cache[key] || null
}
const setItem = async (key, val) => {
await pause(delay)
cache[key] = val
}
return { getItem, setItem, cache }
}

9
src/actions.ts Normal file
View File

@ -0,0 +1,9 @@
import { ApiCall, EntityAction, EntityName, ExtraActionProps } from './types'
export const loadAction = <T>(entity: EntityName, extra: ExtraActionProps<T>): EntityAction<T> => {
return {
entity,
extra,
type: 'GET_FROM_API',
}
}

45
src/context.test.js Normal file
View File

@ -0,0 +1,45 @@
import React from 'react'
import { act, renderHook } from '@testing-library/react-hooks'
import { ApiProvider } from './provider'
import init from './__mocks__/@skolplattformen/embedded-api'
import { useApi } from './context'
describe('useApi()', () => {
let api
beforeEach(() => {
api = init()
})
const wrapper = ({ children }) => (
<ApiProvider api={api}>{children}</ApiProvider>
)
it('exposes api', () => {
const { result } = renderHook(() => useApi(), { wrapper })
expect(result.current.api).toBeTruthy()
})
it('exposes isLoggedIn', () => {
const { result } = renderHook(() => useApi(), { wrapper })
expect(result.current.isLoggedIn).toBe(false)
})
it('updates isLoggedIn', async () => {
const { result, waitForValueToChange } = renderHook(() => useApi(), { wrapper })
await act(async () => {
api.isLoggedIn = true
api.emitter.emit('login')
await waitForValueToChange(() => result.current.isLoggedIn)
})
expect(result.current.isLoggedIn).toBe(true)
})
it('updates isFake', async () => {
const { result, waitForValueToChange } = renderHook(() => useApi(), { wrapper })
await act(async () => {
api.isFake = true
api.emitter.emit('login')
await waitForValueToChange(() => result.current.isFake)
})
expect(result.current.isFake).toBe(true)
})
})

6
src/context.ts Normal file
View File

@ -0,0 +1,6 @@
import { createContext, useContext } from 'react'
import { IApiContext } from './types'
export const ApiContext = createContext<IApiContext>({} as IApiContext)
export const useApi = () => useContext(ApiContext)

134
src/hooks.ts Normal file
View File

@ -0,0 +1,134 @@
import React, { useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'
import { Api, CalendarItem, Child, Classmate, MenuItem, NewsItem, Notification, ScheduleItem, User } from '@skolplattformen/embedded-api'
import {
ApiCall,
EntityHookResult,
EntityMap,
EntityName,
EntityStoreRootState,
ExtraActionProps
} from './types'
import { useApi } from './context'
import { loadAction } from './actions'
import store from './store'
interface StoreSelector<T> {
(state: EntityStoreRootState): EntityMap<T>
}
const hook = <T>(
entityName: EntityName,
key: string,
defaultValue: T,
selector: StoreSelector<T>,
apiCaller: (api: Api) => ApiCall<T>,
): EntityHookResult<T> => {
const select = (storeState: EntityStoreRootState) => {
const stateMap = selector(storeState) || {}
const state = stateMap[key] || { status: 'pending', data: defaultValue }
return state
}
const { api, storage, isLoggedIn } = useApi()
const initialState = select(store.getState() as EntityStoreRootState)
const [state, setState] = useState(initialState)
const dispatch = useDispatch()
const load = (force = false) => {
if (isLoggedIn && (force || state.status === 'pending')) {
const extra: ExtraActionProps<T> = {
key,
defaultValue,
apiCall: apiCaller(api),
}
// Only get from cache first time
if (state.status === 'pending') {
extra.getFromCache = () => storage.getItem(key)
}
// Only save real data to cache
if (!api.isFake) {
extra.saveToCache = (value: string) => storage.setItem(key, value)
}
const action = loadAction<T>(entityName, extra)
dispatch(action)
}
}
useEffect(() => { load() }, [isLoggedIn])
const listener = () => {
const newState = select(store.getState() as EntityStoreRootState)
if (newState.status !== state.status || newState.data !== state.data || newState.error !== state.error) {
setState(newState)
}
}
useEffect(() => store.subscribe(listener), [])
return {
...state,
reload: () => load(true)
}
}
export const useChildList = () => hook<Child[]>(
'CHILDREN',
'children',
[],
(store) => store.children,
(api) => () => api.getChildren(),
)
export const useCalendar = (child: Child) => hook<CalendarItem[]>(
'CALENDAR',
`calendar_${child.id}`,
[],
(store) => store.calendar,
(api) => () => api.getCalendar(child),
)
export const useClassmates = (child: Child) => hook<Classmate[]>(
'CLASSMATES',
`classmates_${child.id}`,
[],
(store) => store.classmates,
(api) => () => api.getClassmates(child),
)
export const useMenu = (child: Child) => hook<MenuItem[]>(
'MENU',
`menu_${child.id}`,
[],
(store) => store.menu,
(api) => () => api.getMenu(child),
)
export const useNews = (child: Child) => hook<NewsItem[]>(
'NEWS',
`news_${child.id}`,
[],
(store) => store.news,
(api) => () => api.getNews(child),
)
export const useNotifications = (child: Child) => hook<Notification[]>(
'NOTIFICATIONS',
`notifications_${child.id}`,
[],
(store) => store.notifications,
(api) => () => api.getNotifications(child),
)
export const useSchedule = (child: Child, from: string, to: string) => hook<ScheduleItem[]>(
'SCHEDULE',
`schedule_${child.id}_${from}_${to}`,
[],
(store) => store.schedule,
(api) => () => api.getSchedule(child, from, to),
)
export const useUser = () => hook<User>(
'USER',
'user',
{},
(store) => store.user,
(api) => () => api.getUser(),
)

1
src/index.ts Normal file
View File

@ -0,0 +1 @@
export * from './provider'

81
src/middleware.ts Normal file
View File

@ -0,0 +1,81 @@
import { Middleware } from 'redux'
import { EntityAction, EntityStoreRootState } from './types'
export const apiMiddleware: Middleware<{}, EntityStoreRootState> =
(storeApi) =>
(next) =>
(action: EntityAction<any>) => {
try {
switch (action.type) {
case 'GET_FROM_API': {
// Call api
const apiCall = action.extra?.apiCall
if (apiCall) {
apiCall()
.then((res: any) => {
const resultAction: EntityAction<any> = {
...action,
type: 'RESULT_FROM_API',
data: res
}
storeApi.dispatch(resultAction)
if (action.extra?.saveToCache && res) {
const cacheAction: EntityAction<any> = {
...resultAction,
type: 'STORE_IN_CACHE'
}
storeApi.dispatch(cacheAction)
}
})
}
// Retrieve from cache
if (action.extra?.getFromCache) {
const cacheAction: EntityAction<any> = {
...action,
type: 'GET_FROM_CACHE'
}
storeApi.dispatch(cacheAction)
}
}
}
} catch (err) {
console.error(err)
}
return next(action)
}
export const cacheMiddleware: Middleware<{}, EntityStoreRootState> =
(storeApi) =>
(next) =>
(action: EntityAction<any>) => {
try {
switch (action.type) {
case 'GET_FROM_CACHE': {
const getFromCache = action.extra?.getFromCache
if (getFromCache) {
getFromCache().then((res: string | null) => {
if (res) {
const cacheResultAction: EntityAction<any> = {
...action,
type: 'RESULT_FROM_CACHE',
data: JSON.parse(res)
}
storeApi.dispatch(cacheResultAction)
}
})
}
}
case 'STORE_IN_CACHE': {
const saveToCache = action.extra?.saveToCache
if (saveToCache && action.data) {
saveToCache(JSON.stringify(action.data))
}
}
}
} catch (err) {
console.error(err)
}
return next(action)
}

25
src/provider.test.jsx Normal file
View File

@ -0,0 +1,25 @@
import React from 'react'
import { render } from '@testing-library/react'
import { ApiProvider } from './provider'
import init from './__mocks__/@skolplattformen/embedded-api'
import { useApi } from './context'
describe('ApiProvider', () => {
const Login = () => {
const { isLoggedIn } = useApi()
return (
<div>
<div data-testid="isLoggedIn">{isLoggedIn ? 'y' : 'n'}</div>
</div>
)
}
let api
beforeEach(() => {
api = init()
})
it('enables useApi()', () => {
const { getByTestId } = render(<ApiProvider api={api}><Login /></ApiProvider>)
expect(getByTestId('isLoggedIn').textContent).toEqual('n')
})
})

43
src/provider.tsx Normal file
View File

@ -0,0 +1,43 @@
import { Api } from '@skolplattformen/embedded-api';
import React, { FC, PropsWithChildren, useEffect, useState } from 'react'
import { Provider } from 'react-redux'
import { ApiContext } from './context'
import store from './store'
import { AsyncStorage, IApiContext } from './types';
type TApiProvider = FC<PropsWithChildren<{ api: Api, storage: AsyncStorage }>>
export const ApiProvider: TApiProvider = ({ children, api, storage }) => {
const [isLoggedIn, setIsLoggedIn] = useState(api.isLoggedIn)
const [isFake, setIsFake] = useState(api.isFake)
const value: IApiContext = {
api,
storage,
isLoggedIn,
isFake,
}
useEffect(() => {
const handler = () => {
setIsLoggedIn(api.isLoggedIn)
setIsFake(api.isFake)
}
api.on('login', handler)
api.on('logout', handler)
return () => {
api.off('login', handler)
api.off('logout', handler)
}
}, [api.isLoggedIn, api.isFake])
return (
<ApiContext.Provider value={value}>
<Provider store={store}>
{children}
</Provider>
</ApiContext.Provider>
)
}

65
src/reducers.ts Normal file
View File

@ -0,0 +1,65 @@
import {
CalendarItem,
Child,
Classmate,
MenuItem,
NewsItem,
Notification,
ScheduleItem,
User,
} from '@skolplattformen/embedded-api'
import { EntityName, EntityReducer, EntityState } from './types'
const createReducer = <T>(entity: EntityName): EntityReducer<T> => {
const reducer: EntityReducer<T> = (state = {}, action) => {
if (action.entity !== entity || !action.extra)
return state
const key = action.extra?.key
const node = state[key] || {
status: 'pending',
data: action.extra.defaultValue,
}
let newNode: EntityState<T>
switch (action.type) {
case 'GET_FROM_API': {
newNode = {
...node,
error: undefined,
status: 'loading',
}
break
}
case 'RESULT_FROM_API': {
newNode = {
...node,
data: action.data || node.data,
status: 'loaded',
}
}
case 'RESULT_FROM_CACHE': {
newNode = {
...node,
data: action.data || node.data,
}
}
default: {
newNode = { ...node }
}
}
return {
...state,
[key]: newNode,
}
}
return reducer
}
export const user = createReducer<User>('USER')
export const children = createReducer<Child[]>('CHILDREN')
export const calendar = createReducer<CalendarItem[]>('CALENDAR')
export const classmates = createReducer<Classmate[]>('CLASSMATES')
export const menu = createReducer<MenuItem[]>('MENU')
export const news = createReducer<NewsItem[]>('NEWS')
export const notifications = createReducer<Notification[]>('NOTIFICATIONS')
export const schedule = createReducer<ScheduleItem[]>('SCHEDULE')

34
src/store.ts Normal file
View File

@ -0,0 +1,34 @@
import { createStore, combineReducers, applyMiddleware } from 'redux'
import { apiMiddleware, cacheMiddleware } from './middleware'
import {
calendar,
children,
classmates,
menu,
news,
notifications,
schedule,
user,
} from './reducers'
import { EntityAction } from './types'
const appReducer = combineReducers({
calendar,
children,
classmates,
menu,
news,
notifications,
schedule,
user,
})
const rootReducer = (state: unknown, action: EntityAction<any>) => {
if (action.type === 'CLEAR') {
state = undefined
}
return appReducer(state, action)
}
const enhancers = applyMiddleware(apiMiddleware, cacheMiddleware)
const store = createStore(rootReducer, enhancers)
export default store

77
src/types.ts Normal file
View File

@ -0,0 +1,77 @@
import {
Api,
Child,
User,
CalendarItem,
Classmate,
MenuItem,
NewsItem,
Notification,
ScheduleItem
} from '@skolplattformen/embedded-api'
import { Action, Reducer } from 'redux'
export interface IApiContext {
api: Api
storage: AsyncStorage
isLoggedIn: boolean
isFake: boolean
}
export type EntityStatus = 'pending' | 'loading' | 'loaded' | 'error'
export interface EntityState<T> {
data: T
status: EntityStatus
error?: Error
}
export interface ApiCall<T> {
(): Promise<T>
}
export interface ExtraActionProps<T> {
apiCall: ApiCall<T>
key: string
defaultValue: T
getFromCache?: () => Promise<string | null>
saveToCache?: (value: string) => Promise<void>
}
export type EntityActionType = 'GET_FROM_API' | 'RESULT_FROM_API' | 'GET_FROM_CACHE' | 'RESULT_FROM_CACHE' | 'STORE_IN_CACHE' | 'CLEAR'
export type EntityName = 'USER'
| 'CHILDREN'
| 'CALENDAR'
| 'CLASSMATES'
| 'MENU'
| 'NEWS'
| 'NOTIFICATIONS'
| 'SCHEDULE'
| 'ALL'
export interface EntityAction<T> extends Action<EntityActionType> {
entity: EntityName
data?: T
error?: Error
extra?: ExtraActionProps<T>
}
export interface EntityMap<T> {
[key: string]: EntityState<T>
}
export type EntityReducer<T> = Reducer<EntityMap<T>, EntityAction<T>>
export interface EntityStoreRootState {
children: EntityMap<Child[]>
user: EntityMap<User>
calendar: EntityMap<CalendarItem[]>,
classmates: EntityMap<Classmate[]>,
menu: EntityMap<MenuItem[]>,
news: EntityMap<NewsItem[]>,
notifications: EntityMap<Notification[]>,
schedule: EntityMap<ScheduleItem[]>,
}
export interface EntityHookResult<T> extends EntityState<T> {
reload: () => void
}
export interface AsyncStorage {
getItem(key: string): Promise<string | null>
setItem(key: string, value: string): Promise<void>
}

136
src/useCalendar.test.js Normal file
View File

@ -0,0 +1,136 @@
import React from 'react'
import { renderHook, act } from '@testing-library/react-hooks'
import { ApiProvider } from './provider'
import { useCalendar } from './hooks'
import store from './store'
import init from './__mocks__/@skolplattformen/embedded-api'
import createStorage from './__mocks__/AsyncStorage'
const pause = (ms = 0) => new Promise(r => setTimeout(r, ms))
describe('useCalendar(child)', () => {
let api
let storage
let result
let child
const wrapper = ({ children }) => (
<ApiProvider api={api} storage={storage}>{children}</ApiProvider>
)
beforeEach(() => {
result = [{ id: 1 }]
api = init()
api.getCalendar.mockImplementation(() => (
new Promise((res) => {
setTimeout(() => res(result), 50)
})
))
storage = createStorage({
calendar_10: [{ id: 2 }]
}, 2)
child = { id: 10 }
})
afterEach(async () => {
await act(async () => {
await pause(70)
store.dispatch({ entity: 'ALL', type: 'CLEAR' })
})
})
it('returns correct initial value', () => {
const { result } = renderHook(() => useCalendar(child), { wrapper })
expect(result.current.status).toEqual('pending')
})
it('calls api', async () => {
await act(async () => {
api.isLoggedIn = true
const { waitForNextUpdate } = renderHook(() => useCalendar(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
expect(api.getCalendar).toHaveBeenCalled()
})
})
it('only calls api once', async () => {
await act(async () => {
api.isLoggedIn = true
renderHook(() => useCalendar(child), { wrapper })
const { waitForNextUpdate } = renderHook(() => useCalendar(child), { wrapper })
await waitForNextUpdate()
renderHook(() => useCalendar(child), { wrapper })
await waitForNextUpdate()
renderHook(() => useCalendar(child), { wrapper })
await waitForNextUpdate()
const { result } = renderHook(() => useCalendar(child), { wrapper })
expect(api.getCalendar).toHaveBeenCalledTimes(1)
expect(result.current.status).toEqual('loaded')
})
})
it('calls cache', async () => {
await act(async () => {
api.isLoggedIn = true
const { result, waitForNextUpdate } = renderHook(() => useCalendar(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
expect(result.current.data).toEqual([{ id: 2 }])
})
})
it('updates status to loading', async () => {
await act(async () => {
api.isLoggedIn = true
const { result, waitForNextUpdate } = renderHook(() => useCalendar(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
expect(result.current.status).toEqual('loading')
})
})
it('updates status to loaded', async () => {
await act(async () => {
api.isLoggedIn = true
const { result, waitForNextUpdate } = renderHook(() => useCalendar(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
await waitForNextUpdate()
expect(result.current.status).toEqual('loaded')
})
})
it('stores in cache if not fake', async () => {
await act(async () => {
api.isLoggedIn = true
api.isFake = false
const { waitForNextUpdate } = renderHook(() => useCalendar(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
await waitForNextUpdate()
await pause(20)
expect(storage.cache['calendar_10']).toEqual('[{"id":1}]')
})
})
it('does not store in cache if fake', async () => {
await act(async () => {
api.isLoggedIn = true
api.isFake = true
const { waitForNextUpdate } = renderHook(() => useCalendar(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
await waitForNextUpdate()
await pause(20)
expect(storage.cache['calendar_10']).toEqual('[{"id":2}]')
})
})
})

134
src/useChildlist.test.js Normal file
View File

@ -0,0 +1,134 @@
import React from 'react'
import { renderHook, act } from '@testing-library/react-hooks'
import { ApiProvider } from './provider'
import { useChildList } from './hooks'
import store from './store'
import init from './__mocks__/@skolplattformen/embedded-api'
import createStorage from './__mocks__/AsyncStorage'
const pause = (ms = 0) => new Promise(r => setTimeout(r, ms))
describe('useChildList()', () => {
let api
let storage
let result
const wrapper = ({ children }) => (
<ApiProvider api={api} storage={storage}>{children}</ApiProvider>
)
beforeEach(() => {
result = [{ id: 1 }]
api = init()
api.getChildren.mockImplementation(() => (
new Promise((res) => {
setTimeout(() => res(result), 50)
})
))
storage = createStorage({
children: [{ id: 2 }]
}, 2)
})
afterEach(async () => {
await act(async () => {
await pause(70)
store.dispatch({ entity: 'ALL', type: 'CLEAR' })
})
})
it('returns correct initial value', () => {
const { result } = renderHook(() => useChildList(), { wrapper })
expect(result.current.status).toEqual('pending')
})
it('calls api', async () => {
await act(async () => {
api.isLoggedIn = true
const { waitForNextUpdate } = renderHook(() => useChildList(), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
expect(api.getChildren).toHaveBeenCalled()
})
})
it('only calls api once', async () => {
await act(async () => {
api.isLoggedIn = true
renderHook(() => useChildList(), { wrapper })
const { waitForNextUpdate } = renderHook(() => useChildList(), { wrapper })
await waitForNextUpdate()
renderHook(() => useChildList(), { wrapper })
await waitForNextUpdate()
renderHook(() => useChildList(), { wrapper })
await waitForNextUpdate()
const { result } = renderHook(() => useChildList(), { wrapper })
expect(api.getChildren).toHaveBeenCalledTimes(1)
expect(result.current.status).toEqual('loaded')
})
})
it('calls cache', async () => {
await act(async () => {
api.isLoggedIn = true
const { result, waitForNextUpdate } = renderHook(() => useChildList(), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
expect(result.current.data).toEqual([{ id: 2 }])
})
})
it('updates status to loading', async () => {
await act(async () => {
api.isLoggedIn = true
const { result, waitForNextUpdate } = renderHook(() => useChildList(), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
expect(result.current.status).toEqual('loading')
})
})
it('updates status to loaded', async () => {
await act(async () => {
api.isLoggedIn = true
const { result, waitForNextUpdate } = renderHook(() => useChildList(), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
await waitForNextUpdate()
expect(result.current.status).toEqual('loaded')
})
})
it('stores in cache if not fake', async () => {
await act(async () => {
api.isLoggedIn = true
api.isFake = false
const { waitForNextUpdate } = renderHook(() => useChildList(), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
await waitForNextUpdate()
await pause(20)
expect(storage.cache['children']).toEqual('[{"id":1}]')
})
})
it('does not store in cache if fake', async () => {
await act(async () => {
api.isLoggedIn = true
api.isFake = true
const { waitForNextUpdate } = renderHook(() => useChildList(), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
await waitForNextUpdate()
await pause(20)
expect(storage.cache['children']).toEqual('[{"id":2}]')
})
})
})

136
src/useClassmates.test.js Normal file
View File

@ -0,0 +1,136 @@
import React from 'react'
import { renderHook, act } from '@testing-library/react-hooks'
import { ApiProvider } from './provider'
import { useClassmates } from './hooks'
import store from './store'
import init from './__mocks__/@skolplattformen/embedded-api'
import createStorage from './__mocks__/AsyncStorage'
const pause = (ms = 0) => new Promise(r => setTimeout(r, ms))
describe('useClassmates(child)', () => {
let api
let storage
let result
let child
const wrapper = ({ children }) => (
<ApiProvider api={api} storage={storage}>{children}</ApiProvider>
)
beforeEach(() => {
result = [{ id: 1 }]
api = init()
api.getClassmates.mockImplementation(() => (
new Promise((res) => {
setTimeout(() => res(result), 50)
})
))
storage = createStorage({
classmates_10: [{ id: 2 }]
}, 2)
child = { id: 10 }
})
afterEach(async () => {
await act(async () => {
await pause(70)
store.dispatch({ entity: 'ALL', type: 'CLEAR' })
})
})
it('returns correct initial value', () => {
const { result } = renderHook(() => useClassmates(child), { wrapper })
expect(result.current.status).toEqual('pending')
})
it('calls api', async () => {
await act(async () => {
api.isLoggedIn = true
const { waitForNextUpdate } = renderHook(() => useClassmates(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
expect(api.getClassmates).toHaveBeenCalled()
})
})
it('only calls api once', async () => {
await act(async () => {
api.isLoggedIn = true
renderHook(() => useClassmates(child), { wrapper })
const { waitForNextUpdate } = renderHook(() => useClassmates(child), { wrapper })
await waitForNextUpdate()
renderHook(() => useClassmates(child), { wrapper })
await waitForNextUpdate()
renderHook(() => useClassmates(child), { wrapper })
await waitForNextUpdate()
const { result } = renderHook(() => useClassmates(child), { wrapper })
expect(api.getClassmates).toHaveBeenCalledTimes(1)
expect(result.current.status).toEqual('loaded')
})
})
it('calls cache', async () => {
await act(async () => {
api.isLoggedIn = true
const { result, waitForNextUpdate } = renderHook(() => useClassmates(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
expect(result.current.data).toEqual([{ id: 2 }])
})
})
it('updates status to loading', async () => {
await act(async () => {
api.isLoggedIn = true
const { result, waitForNextUpdate } = renderHook(() => useClassmates(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
expect(result.current.status).toEqual('loading')
})
})
it('updates status to loaded', async () => {
await act(async () => {
api.isLoggedIn = true
const { result, waitForNextUpdate } = renderHook(() => useClassmates(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
await waitForNextUpdate()
expect(result.current.status).toEqual('loaded')
})
})
it('stores in cache if not fake', async () => {
await act(async () => {
api.isLoggedIn = true
api.isFake = false
const { waitForNextUpdate } = renderHook(() => useClassmates(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
await waitForNextUpdate()
await pause(20)
expect(storage.cache['classmates_10']).toEqual('[{"id":1}]')
})
})
it('does not store in cache if fake', async () => {
await act(async () => {
api.isLoggedIn = true
api.isFake = true
const { waitForNextUpdate } = renderHook(() => useClassmates(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
await waitForNextUpdate()
await pause(20)
expect(storage.cache['classmates_10']).toEqual('[{"id":2}]')
})
})
})

136
src/useMenu.test.js Normal file
View File

@ -0,0 +1,136 @@
import React from 'react'
import { renderHook, act } from '@testing-library/react-hooks'
import { ApiProvider } from './provider'
import { useMenu } from './hooks'
import store from './store'
import init from './__mocks__/@skolplattformen/embedded-api'
import createStorage from './__mocks__/AsyncStorage'
const pause = (ms = 0) => new Promise(r => setTimeout(r, ms))
describe('useMenu(child)', () => {
let api
let storage
let result
let child
const wrapper = ({ children }) => (
<ApiProvider api={api} storage={storage}>{children}</ApiProvider>
)
beforeEach(() => {
result = [{ id: 1 }]
api = init()
api.getMenu.mockImplementation(() => (
new Promise((res) => {
setTimeout(() => res(result), 50)
})
))
storage = createStorage({
menu_10: [{ id: 2 }]
}, 2)
child = { id: 10 }
})
afterEach(async () => {
await act(async () => {
await pause(70)
store.dispatch({ entity: 'ALL', type: 'CLEAR' })
})
})
it('returns correct initial value', () => {
const { result } = renderHook(() => useMenu(child), { wrapper })
expect(result.current.status).toEqual('pending')
})
it('calls api', async () => {
await act(async () => {
api.isLoggedIn = true
const { waitForNextUpdate } = renderHook(() => useMenu(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
expect(api.getMenu).toHaveBeenCalled()
})
})
it('only calls api once', async () => {
await act(async () => {
api.isLoggedIn = true
renderHook(() => useMenu(child), { wrapper })
const { waitForNextUpdate } = renderHook(() => useMenu(child), { wrapper })
await waitForNextUpdate()
renderHook(() => useMenu(child), { wrapper })
await waitForNextUpdate()
renderHook(() => useMenu(child), { wrapper })
await waitForNextUpdate()
const { result } = renderHook(() => useMenu(child), { wrapper })
expect(api.getMenu).toHaveBeenCalledTimes(1)
expect(result.current.status).toEqual('loaded')
})
})
it('calls cache', async () => {
await act(async () => {
api.isLoggedIn = true
const { result, waitForNextUpdate } = renderHook(() => useMenu(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
expect(result.current.data).toEqual([{ id: 2 }])
})
})
it('updates status to loading', async () => {
await act(async () => {
api.isLoggedIn = true
const { result, waitForNextUpdate } = renderHook(() => useMenu(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
expect(result.current.status).toEqual('loading')
})
})
it('updates status to loaded', async () => {
await act(async () => {
api.isLoggedIn = true
const { result, waitForNextUpdate } = renderHook(() => useMenu(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
await waitForNextUpdate()
expect(result.current.status).toEqual('loaded')
})
})
it('stores in cache if not fake', async () => {
await act(async () => {
api.isLoggedIn = true
api.isFake = false
const { waitForNextUpdate } = renderHook(() => useMenu(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
await waitForNextUpdate()
await pause(20)
expect(storage.cache['menu_10']).toEqual('[{"id":1}]')
})
})
it('does not store in cache if fake', async () => {
await act(async () => {
api.isLoggedIn = true
api.isFake = true
const { waitForNextUpdate } = renderHook(() => useMenu(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
await waitForNextUpdate()
await pause(20)
expect(storage.cache['menu_10']).toEqual('[{"id":2}]')
})
})
})

136
src/useNews.test.js Normal file
View File

@ -0,0 +1,136 @@
import React from 'react'
import { renderHook, act } from '@testing-library/react-hooks'
import { ApiProvider } from './provider'
import { useNews } from './hooks'
import store from './store'
import init from './__mocks__/@skolplattformen/embedded-api'
import createStorage from './__mocks__/AsyncStorage'
const pause = (ms = 0) => new Promise(r => setTimeout(r, ms))
describe('useNews(child)', () => {
let api
let storage
let result
let child
const wrapper = ({ children }) => (
<ApiProvider api={api} storage={storage}>{children}</ApiProvider>
)
beforeEach(() => {
result = [{ id: 1 }]
api = init()
api.getNews.mockImplementation(() => (
new Promise((res) => {
setTimeout(() => res(result), 50)
})
))
storage = createStorage({
news_10: [{ id: 2 }]
}, 2)
child = { id: 10 }
})
afterEach(async () => {
await act(async () => {
await pause(70)
store.dispatch({ entity: 'ALL', type: 'CLEAR' })
})
})
it('returns correct initial value', () => {
const { result } = renderHook(() => useNews(child), { wrapper })
expect(result.current.status).toEqual('pending')
})
it('calls api', async () => {
await act(async () => {
api.isLoggedIn = true
const { waitForNextUpdate } = renderHook(() => useNews(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
expect(api.getNews).toHaveBeenCalled()
})
})
it('only calls api once', async () => {
await act(async () => {
api.isLoggedIn = true
renderHook(() => useNews(child), { wrapper })
const { waitForNextUpdate } = renderHook(() => useNews(child), { wrapper })
await waitForNextUpdate()
renderHook(() => useNews(child), { wrapper })
await waitForNextUpdate()
renderHook(() => useNews(child), { wrapper })
await waitForNextUpdate()
const { result } = renderHook(() => useNews(child), { wrapper })
expect(api.getNews).toHaveBeenCalledTimes(1)
expect(result.current.status).toEqual('loaded')
})
})
it('calls cache', async () => {
await act(async () => {
api.isLoggedIn = true
const { result, waitForNextUpdate } = renderHook(() => useNews(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
expect(result.current.data).toEqual([{ id: 2 }])
})
})
it('updates status to loading', async () => {
await act(async () => {
api.isLoggedIn = true
const { result, waitForNextUpdate } = renderHook(() => useNews(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
expect(result.current.status).toEqual('loading')
})
})
it('updates status to loaded', async () => {
await act(async () => {
api.isLoggedIn = true
const { result, waitForNextUpdate } = renderHook(() => useNews(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
await waitForNextUpdate()
expect(result.current.status).toEqual('loaded')
})
})
it('stores in cache if not fake', async () => {
await act(async () => {
api.isLoggedIn = true
api.isFake = false
const { waitForNextUpdate } = renderHook(() => useNews(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
await waitForNextUpdate()
await pause(20)
expect(storage.cache['news_10']).toEqual('[{"id":1}]')
})
})
it('does not store in cache if fake', async () => {
await act(async () => {
api.isLoggedIn = true
api.isFake = true
const { waitForNextUpdate } = renderHook(() => useNews(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
await waitForNextUpdate()
await pause(20)
expect(storage.cache['news_10']).toEqual('[{"id":2}]')
})
})
})

View File

@ -0,0 +1,136 @@
import React from 'react'
import { renderHook, act } from '@testing-library/react-hooks'
import { ApiProvider } from './provider'
import { useNotifications } from './hooks'
import store from './store'
import init from './__mocks__/@skolplattformen/embedded-api'
import createStorage from './__mocks__/AsyncStorage'
const pause = (ms = 0) => new Promise(r => setTimeout(r, ms))
describe('useNotifications(child)', () => {
let api
let storage
let result
let child
const wrapper = ({ children }) => (
<ApiProvider api={api} storage={storage}>{children}</ApiProvider>
)
beforeEach(() => {
result = [{ id: 1 }]
api = init()
api.getNotifications.mockImplementation(() => (
new Promise((res) => {
setTimeout(() => res(result), 50)
})
))
storage = createStorage({
notifications_10: [{ id: 2 }]
}, 2)
child = { id: 10 }
})
afterEach(async () => {
await act(async () => {
await pause(70)
store.dispatch({ entity: 'ALL', type: 'CLEAR' })
})
})
it('returns correct initial value', () => {
const { result } = renderHook(() => useNotifications(child), { wrapper })
expect(result.current.status).toEqual('pending')
})
it('calls api', async () => {
await act(async () => {
api.isLoggedIn = true
const { waitForNextUpdate } = renderHook(() => useNotifications(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
expect(api.getNotifications).toHaveBeenCalled()
})
})
it('only calls api once', async () => {
await act(async () => {
api.isLoggedIn = true
renderHook(() => useNotifications(child), { wrapper })
const { waitForNextUpdate } = renderHook(() => useNotifications(child), { wrapper })
await waitForNextUpdate()
renderHook(() => useNotifications(child), { wrapper })
await waitForNextUpdate()
renderHook(() => useNotifications(child), { wrapper })
await waitForNextUpdate()
const { result } = renderHook(() => useNotifications(child), { wrapper })
expect(api.getNotifications).toHaveBeenCalledTimes(1)
expect(result.current.status).toEqual('loaded')
})
})
it('calls cache', async () => {
await act(async () => {
api.isLoggedIn = true
const { result, waitForNextUpdate } = renderHook(() => useNotifications(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
expect(result.current.data).toEqual([{ id: 2 }])
})
})
it('updates status to loading', async () => {
await act(async () => {
api.isLoggedIn = true
const { result, waitForNextUpdate } = renderHook(() => useNotifications(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
expect(result.current.status).toEqual('loading')
})
})
it('updates status to loaded', async () => {
await act(async () => {
api.isLoggedIn = true
const { result, waitForNextUpdate } = renderHook(() => useNotifications(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
await waitForNextUpdate()
expect(result.current.status).toEqual('loaded')
})
})
it('stores in cache if not fake', async () => {
await act(async () => {
api.isLoggedIn = true
api.isFake = false
const { waitForNextUpdate } = renderHook(() => useNotifications(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
await waitForNextUpdate()
await pause(20)
expect(storage.cache['notifications_10']).toEqual('[{"id":1}]')
})
})
it('does not store in cache if fake', async () => {
await act(async () => {
api.isLoggedIn = true
api.isFake = true
const { waitForNextUpdate } = renderHook(() => useNotifications(child), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
await waitForNextUpdate()
await pause(20)
expect(storage.cache['notifications_10']).toEqual('[{"id":2}]')
})
})
})

140
src/useSchedule.test.js Normal file
View File

@ -0,0 +1,140 @@
import React from 'react'
import { renderHook, act } from '@testing-library/react-hooks'
import { ApiProvider } from './provider'
import { useSchedule } from './hooks'
import store from './store'
import init from './__mocks__/@skolplattformen/embedded-api'
import createStorage from './__mocks__/AsyncStorage'
const pause = (ms = 0) => new Promise(r => setTimeout(r, ms))
describe('useSchedule(child, from, to)', () => {
let api
let storage
let result
let child
let from
let to
const wrapper = ({ children }) => (
<ApiProvider api={api} storage={storage}>{children}</ApiProvider>
)
beforeEach(() => {
result = [{ id: 1 }]
api = init()
api.getSchedule.mockImplementation(() => (
new Promise((res) => {
setTimeout(() => res(result), 50)
})
))
storage = createStorage({
'schedule_10_2021-01-01_2021-01-08': [{ id: 2 }]
}, 2)
child = { id: 10 }
from = '2021-01-01'
to = '2021-01-08'
})
afterEach(async () => {
await act(async () => {
await pause(70)
store.dispatch({ entity: 'ALL', type: 'CLEAR' })
})
})
it('returns correct initial value', () => {
const { result } = renderHook(() => useSchedule(child, from, to), { wrapper })
expect(result.current.status).toEqual('pending')
})
it('calls api', async () => {
await act(async () => {
api.isLoggedIn = true
const { waitForNextUpdate } = renderHook(() => useSchedule(child, from, to), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
expect(api.getSchedule).toHaveBeenCalled()
})
})
it('only calls api once', async () => {
await act(async () => {
api.isLoggedIn = true
renderHook(() => useSchedule(child, from, to), { wrapper })
const { waitForNextUpdate } = renderHook(() => useSchedule(child, from, to), { wrapper })
await waitForNextUpdate()
renderHook(() => useSchedule(child, from, to), { wrapper })
await waitForNextUpdate()
renderHook(() => useSchedule(child, from, to), { wrapper })
await waitForNextUpdate()
const { result } = renderHook(() => useSchedule(child, from, to), { wrapper })
expect(api.getSchedule).toHaveBeenCalledTimes(1)
expect(result.current.status).toEqual('loaded')
})
})
it('calls cache', async () => {
await act(async () => {
api.isLoggedIn = true
const { result, waitForNextUpdate } = renderHook(() => useSchedule(child, from, to), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
expect(result.current.data).toEqual([{ id: 2 }])
})
})
it('updates status to loading', async () => {
await act(async () => {
api.isLoggedIn = true
const { result, waitForNextUpdate } = renderHook(() => useSchedule(child, from, to), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
expect(result.current.status).toEqual('loading')
})
})
it('updates status to loaded', async () => {
await act(async () => {
api.isLoggedIn = true
const { result, waitForNextUpdate } = renderHook(() => useSchedule(child, from, to), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
await waitForNextUpdate()
expect(result.current.status).toEqual('loaded')
})
})
it('stores in cache if not fake', async () => {
await act(async () => {
api.isLoggedIn = true
api.isFake = false
const { waitForNextUpdate } = renderHook(() => useSchedule(child, from, to), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
await waitForNextUpdate()
await pause(20)
expect(storage.cache['schedule_10_2021-01-01_2021-01-08']).toEqual('[{"id":1}]')
})
})
it('does not store in cache if fake', async () => {
await act(async () => {
api.isLoggedIn = true
api.isFake = true
const { waitForNextUpdate } = renderHook(() => useSchedule(child, from, to), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
await waitForNextUpdate()
await pause(20)
expect(storage.cache['schedule_10_2021-01-01_2021-01-08']).toEqual('[{"id":2}]')
})
})
})

134
src/useUser.test.js Normal file
View File

@ -0,0 +1,134 @@
import React from 'react'
import { renderHook, act } from '@testing-library/react-hooks'
import { ApiProvider } from './provider'
import { useUser } from './hooks'
import store from './store'
import init from './__mocks__/@skolplattformen/embedded-api'
import createStorage from './__mocks__/AsyncStorage'
const pause = (ms = 0) => new Promise(r => setTimeout(r, ms))
describe('useUser()', () => {
let api
let storage
let result
const wrapper = ({ children }) => (
<ApiProvider api={api} storage={storage}>{children}</ApiProvider>
)
beforeEach(() => {
result = { id: 1 }
api = init()
api.getUser.mockImplementation(() => (
new Promise((res) => {
setTimeout(() => res(result), 50)
})
))
storage = createStorage({
user: { id: 2 }
}, 2)
})
afterEach(async () => {
await act(async () => {
await pause(70)
store.dispatch({ entity: 'ALL', type: 'CLEAR' })
})
})
it('returns correct initial value', () => {
const { result } = renderHook(() => useUser(), { wrapper })
expect(result.current.status).toEqual('pending')
})
it('calls api', async () => {
await act(async () => {
api.isLoggedIn = true
const { waitForNextUpdate } = renderHook(() => useUser(), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
expect(api.getUser).toHaveBeenCalled()
})
})
it('only calls api once', async () => {
await act(async () => {
api.isLoggedIn = true
renderHook(() => useUser(), { wrapper })
const { waitForNextUpdate } = renderHook(() => useUser(), { wrapper })
await waitForNextUpdate()
renderHook(() => useUser(), { wrapper })
await waitForNextUpdate()
renderHook(() => useUser(), { wrapper })
await waitForNextUpdate()
const { result } = renderHook(() => useUser(), { wrapper })
expect(api.getUser).toHaveBeenCalledTimes(1)
expect(result.current.status).toEqual('loaded')
})
})
it('calls cache', async () => {
await act(async () => {
api.isLoggedIn = true
const { result, waitForNextUpdate } = renderHook(() => useUser(), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
expect(result.current.data).toEqual({ id: 2 })
})
})
it('updates status to loading', async () => {
await act(async () => {
api.isLoggedIn = true
const { result, waitForNextUpdate } = renderHook(() => useUser(), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
expect(result.current.status).toEqual('loading')
})
})
it('updates status to loaded', async () => {
await act(async () => {
api.isLoggedIn = true
const { result, waitForNextUpdate } = renderHook(() => useUser(), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
await waitForNextUpdate()
expect(result.current.status).toEqual('loaded')
})
})
it('stores in cache if not fake', async () => {
await act(async () => {
api.isLoggedIn = true
api.isFake = false
const { waitForNextUpdate } = renderHook(() => useUser(), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
await waitForNextUpdate()
await pause(20)
expect(storage.cache['user']).toEqual('{"id":1}')
})
})
it('does not store in cache if fake', async () => {
await act(async () => {
api.isLoggedIn = true
api.isFake = true
const { waitForNextUpdate } = renderHook(() => useUser(), { wrapper })
await waitForNextUpdate()
await waitForNextUpdate()
await waitForNextUpdate()
await pause(20)
expect(storage.cache['user']).toEqual('{"id":2}')
})
})
})

62
tsconfig.json Normal file
View File

@ -0,0 +1,62 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "ES2020", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
"jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
"sourceRoot": "./src", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}

5920
yarn.lock Normal file

File diff suppressed because it is too large Load Diff