Skip to content

Commit 8857a14

Browse files
authored
Merge pull request #4114 from aryaemami59/modernize-unit-test-setup
Modernize unit test setup
2 parents e7a3456 + 21fe9fc commit 8857a14

32 files changed

+763
-426
lines changed

.github/workflows/tests.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ jobs:
9191
- name: Install build artifact
9292
run: yarn workspace @reduxjs/toolkit add $(pwd)/package.tgz
9393

94-
- run: sed -i -e /@remap-prod-remove-line/d ./tsconfig.base.json ./vitest.config.ts ./src/tests/*.* ./src/query/tests/*.*
94+
- run: sed -i -e /@remap-prod-remove-line/d ./tsconfig.base.json ./vitest.config.mts ./src/tests/*.* ./src/query/tests/*.*
9595

9696
- name: Run tests, against dist
9797
run: yarn test
@@ -133,7 +133,7 @@ jobs:
133133
- name: Show installed RTK versions
134134
run: yarn info @reduxjs/toolkit
135135

136-
- run: sed -i -e /@remap-prod-remove-line/d ./tsconfig.base.json ./vitest.config.ts ./src/tests/*.* ./src/query/tests/*.*
136+
- run: sed -i -e /@remap-prod-remove-line/d ./tsconfig.base.json ./vitest.config.mts ./src/tests/*.* ./src/query/tests/*.*
137137

138138
- name: Test types
139139
run: |

.yarn/patches/msw-npm-0.40.2-2107d48752

Lines changed: 0 additions & 20 deletions
This file was deleted.

package.json

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,6 @@
4747
"@babel/types": "7.19.3",
4848
"esbuild": "0.19.7",
4949
"jest-snapshot": "29.3.1",
50-
"msw": "patch:msw@npm:0.40.2#.yarn/patches/msw-npm-0.40.2-2107d48752",
5150
"jscodeshift": "0.13.1",
5251
"react-redux": "npm:8.0.2",
5352
"react": "npm:18.2.0",

packages/toolkit/package.json

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,8 +80,8 @@
8080
"invariant": "^2.2.4",
8181
"jsdom": "^21.0.0",
8282
"json-stringify-safe": "^5.0.1",
83-
"msw": "^0.40.2",
84-
"node-fetch": "^2.6.1",
83+
"msw": "^2.1.4",
84+
"node-fetch": "^3.3.2",
8585
"prettier": "^2.2.1",
8686
"query-string": "^7.0.1",
8787
"rimraf": "^3.0.2",
@@ -101,6 +101,7 @@
101101
"format:check": "prettier --list-different \"(src|examples)/**/*.{ts,tsx}\" \"docs/*/**.md\"",
102102
"lint": "eslint src examples",
103103
"test": "vitest --run",
104+
"test:watch": "vitest --watch",
104105
"type-tests": "yarn tsc -p src/tests/tsconfig.typetests.json && yarn tsc -p src/query/tests/tsconfig.typetests.json",
105106
"prepack": "yarn build"
106107
},

packages/toolkit/src/query/tests/apiProvider.test.tsx

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
1-
import * as React from 'react'
2-
import { createApi, ApiProvider } from '@reduxjs/toolkit/query/react'
1+
import { configureStore } from '@reduxjs/toolkit'
2+
import { ApiProvider, createApi } from '@reduxjs/toolkit/query/react'
33
import { fireEvent, render, waitFor } from '@testing-library/react'
4-
import { waitMs } from './helpers'
4+
import { delay } from 'msw'
5+
import * as React from 'react'
56
import { Provider } from 'react-redux'
6-
import { configureStore } from '@reduxjs/toolkit'
77

88
const api = createApi({
99
baseQuery: async (arg: any) => {
10-
await waitMs()
10+
await delay(150)
1111
return { data: arg?.body ? arg.body : null }
1212
},
1313
endpoints: (build) => ({

packages/toolkit/src/query/tests/buildCreateApi.test.tsx

Lines changed: 12 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,20 @@
1+
import { createSelectorCreator, lruMemoize } from '@reduxjs/toolkit'
2+
import {
3+
buildCreateApi,
4+
coreModule,
5+
reactHooksModule,
6+
} from '@reduxjs/toolkit/query/react'
7+
import { render, screen, waitFor } from '@testing-library/react'
8+
import { delay } from 'msw'
19
import * as React from 'react'
210
import type { ReactReduxContextValue } from 'react-redux'
311
import {
12+
Provider,
413
createDispatchHook,
514
createSelectorHook,
615
createStoreHook,
7-
Provider,
816
} from 'react-redux'
9-
import {
10-
buildCreateApi,
11-
coreModule,
12-
reactHooksModule,
13-
} from '@reduxjs/toolkit/query/react'
14-
import {
15-
act,
16-
fireEvent,
17-
render,
18-
screen,
19-
waitFor,
20-
renderHook,
21-
} from '@testing-library/react'
22-
import userEvent from '@testing-library/user-event'
23-
import { rest } from 'msw'
24-
import {
25-
actionsReducer,
26-
ANY,
27-
expectExactType,
28-
expectType,
29-
setupApiStore,
30-
withProvider,
31-
useRenderCounter,
32-
waitMs,
33-
} from './helpers'
34-
import { server } from './mocks/server'
35-
import type { UnknownAction } from 'redux'
36-
import type { SubscriptionOptions } from '@reduxjs/toolkit/dist/query/core/apiState'
37-
import type { SerializedError } from '@reduxjs/toolkit'
38-
import {
39-
createListenerMiddleware,
40-
configureStore,
41-
lruMemoize,
42-
createSelectorCreator,
43-
} from '@reduxjs/toolkit'
44-
import { delay } from '../../utils'
17+
import { setupApiStore, useRenderCounter } from './helpers'
4518

4619
const MyContext = React.createContext<ReactReduxContextValue>(null as any)
4720

@@ -60,7 +33,7 @@ describe('buildCreateApi', () => {
6033

6134
const api = customCreateApi({
6235
baseQuery: async (arg: any) => {
63-
await waitMs()
36+
await delay(150)
6437

6538
return {
6639
data: arg?.body ? { ...arg.body } : {},
@@ -140,7 +113,7 @@ describe('buildCreateApi', () => {
140113
)
141114
const api = createApi({
142115
baseQuery: async (arg: any) => {
143-
await waitMs()
116+
await delay(150)
144117

145118
return {
146119
data: arg?.body ? { ...arg.body } : {},

packages/toolkit/src/query/tests/buildHooks.test.tsx

Lines changed: 24 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,9 @@ import {
2020
renderHook,
2121
} from '@testing-library/react'
2222
import userEvent from '@testing-library/user-event'
23-
import { rest } from 'msw'
23+
import { http, HttpResponse } from 'msw'
2424
import {
2525
actionsReducer,
26-
ANY,
2726
expectExactType,
2827
expectType,
2928
setupApiStore,
@@ -104,7 +103,7 @@ const api = createApi({
104103
query: (update) => ({ body: update }),
105104
}),
106105
getError: build.query({
107-
query: (query) => '/error',
106+
query: () => '/error',
108107
}),
109108
listItems: build.query<Item[], { pageNumber: number }>({
110109
serializeQueryArgs: ({ endpointName }) => {
@@ -119,7 +118,7 @@ const api = createApi({
119118
merge: (currentCache, newItems) => {
120119
currentCache.push(...newItems)
121120
},
122-
forceRefetch: ({ currentArg, previousArg }) => {
121+
forceRefetch: () => {
123122
return true
124123
},
125124
}),
@@ -757,7 +756,7 @@ describe('hooks tests', () => {
757756
}
758757

759758
// 1) Initial state: an active subscription
760-
const { result, rerender, unmount } = renderHook(
759+
const { rerender, unmount } = renderHook(
761760
([arg, options]: Parameters<
762761
typeof pokemonApi.useGetPokemonByNameQuery
763762
>) => pokemonApi.useGetPokemonByNameQuery(arg, options),
@@ -1752,14 +1751,14 @@ describe('hooks tests', () => {
17521751
test('initially failed useQueries that provide an tag will refetch after a mutation invalidates it', async () => {
17531752
const checkSessionData = { name: 'matt' }
17541753
server.use(
1755-
rest.get('https://example.com/me', (req, res, ctx) => {
1756-
return res.once(ctx.status(500))
1754+
http.get('https://example.com/me', () => {
1755+
return HttpResponse.json(null, { status: 500 })
1756+
}, { once: true }),
1757+
http.get('https://example.com/me', () => {
1758+
return HttpResponse.json(checkSessionData)
17571759
}),
1758-
rest.get('https://example.com/me', (req, res, ctx) => {
1759-
return res(ctx.json(checkSessionData))
1760-
}),
1761-
rest.post('https://example.com/login', (req, res, ctx) => {
1762-
return res(ctx.status(200))
1760+
http.post('https://example.com/login', () => {
1761+
return HttpResponse.json(null, { status: 200 })
17631762
})
17641763
)
17651764
let data, isLoading, isError
@@ -1977,39 +1976,41 @@ describe('hooks with createApi defaults set', () => {
19771976
posts = [...initialPosts]
19781977

19791978
const handlers = [
1980-
rest.get('https://example.com/posts', (req, res, ctx) => {
1981-
return res(ctx.json(posts))
1979+
http.get('https://example.com/posts', () => {
1980+
return HttpResponse.json(posts)
19821981
}),
1983-
rest.put<Partial<Post>>(
1982+
http.put<{ id: string }, Partial<Post>>(
19841983
'https://example.com/post/:id',
1985-
(req, res, ctx) => {
1986-
const id = Number(req.params.id)
1984+
async ({ request, params }) => {
1985+
const body = await request.json();
1986+
const id = Number(params.id)
19871987
const idx = posts.findIndex((post) => post.id === id)
19881988

19891989
const newPosts = posts.map((post, index) =>
19901990
index !== idx
19911991
? post
19921992
: {
1993-
...req.body,
1993+
...body,
19941994
id,
1995-
name: req.body.name || post.name,
1995+
name: body?.name || post.name,
19961996
fetched_at: new Date().toUTCString(),
19971997
}
19981998
)
19991999
posts = [...newPosts]
20002000

2001-
return res(ctx.json(posts))
2001+
return HttpResponse.json(posts)
20022002
}
20032003
),
2004-
rest.post('https://example.com/post', (req, res, ctx) => {
2005-
let post = req.body as Omit<Post, 'id'>
2004+
http.post<any, Omit<Post, 'id'>>('https://example.com/post', async ({ request }) => {
2005+
const body = await request.json();
2006+
let post = body
20062007
startingId += 1
20072008
posts.concat({
20082009
...post,
20092010
fetched_at: new Date().toISOString(),
20102011
id: startingId,
20112012
})
2012-
return res(ctx.json(posts))
2013+
return HttpResponse.json(posts)
20132014
}),
20142015
]
20152016

@@ -2377,11 +2378,6 @@ describe('hooks with createApi defaults set', () => {
23772378

23782379
test('useQuery with selectFromResult option has a type error if the result is not an object', async () => {
23792380
function SelectedPost() {
2380-
const _res1 = api.endpoints.getPosts.useQuery(undefined, {
2381-
// selectFromResult must always return an object
2382-
// @ts-expect-error
2383-
selectFromResult: ({ data }) => data?.length ?? 0,
2384-
})
23852381

23862382
const res2 = api.endpoints.getPosts.useQuery(undefined, {
23872383
// selectFromResult must always return an object

packages/toolkit/src/query/tests/buildMiddleware.test.tsx

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { createApi } from '@reduxjs/toolkit/query'
2-
import { actionsReducer, setupApiStore, waitMs } from './helpers'
2+
import { delay } from 'msw'
3+
import { actionsReducer, setupApiStore } from './helpers'
34

45
const baseQuery = (args?: any) => ({ data: args })
56
const api = createApi({
@@ -43,7 +44,7 @@ it('invalidates the specified tags', async () => {
4344
await storeRef.store.dispatch(api.util.invalidateTags(['Banana', 'Bread']))
4445

4546
// Slight pause to let the middleware run and such
46-
await waitMs(20)
47+
await delay(20)
4748

4849
const firstSequence = [
4950
api.internalActions.middlewareRegistered.match,
@@ -58,7 +59,7 @@ it('invalidates the specified tags', async () => {
5859
await storeRef.store.dispatch(getBread.initiate(1))
5960
await storeRef.store.dispatch(api.util.invalidateTags([{ type: 'Bread' }]))
6061

61-
await waitMs(20)
62+
await delay(20)
6263

6364
expect(storeRef.store.getState().actions).toMatchSequence(
6465
...firstSequence,

packages/toolkit/src/query/tests/buildSlice.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { createSlice } from '@reduxjs/toolkit'
22
import { createApi } from '@reduxjs/toolkit/query'
3+
import { delay } from 'msw'
34
import { setupApiStore } from './helpers'
4-
import { delay } from '../../utils'
55

66
let shouldApiResponseSuccess = true
77

0 commit comments

Comments
 (0)