Skip to content

Commit 6b0eca6

Browse files
committed
Merge branch 'master' of https://github.com/reduxjs/redux-toolkit into fix-type-tests-setup
2 parents 8d54f12 + 8857a14 commit 6b0eca6

27 files changed

+637
-305
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.

packages/toolkit/package.json

Lines changed: 2 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",

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

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

88
const api = createApi({
99
baseQuery: async (arg: any) => {
10-
await waitMs(150)
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: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
reactHooksModule,
66
} from '@reduxjs/toolkit/query/react'
77
import { render, screen, waitFor } from '@testing-library/react'
8+
import { delay } from 'msw'
89
import * as React from 'react'
910
import type { ReactReduxContextValue } from 'react-redux'
1011
import {

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

Lines changed: 27 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,10 @@ import {
2222
renderHook,
2323
screen,
2424
waitFor,
25-
} from '@testing-library/react';
26-
import userEvent from '@testing-library/user-event';
27-
import { rest } from 'msw';
28-
import React from "react";
29-
import type { MockInstance } from "vitest";
25+
renderHook,
26+
} from '@testing-library/react'
27+
import userEvent from '@testing-library/user-event'
28+
import { http, HttpResponse } from 'msw'
3029
import {
3130
actionsReducer,
3231
setupApiStore,
@@ -103,7 +102,7 @@ const api = createApi({
103102
query: (update) => ({ body: update }),
104103
}),
105104
getError: build.query({
106-
query: (query) => '/error',
105+
query: () => '/error',
107106
}),
108107
listItems: build.query<Item[], { pageNumber: number }>({
109108
serializeQueryArgs: ({ endpointName }) => {
@@ -118,7 +117,7 @@ const api = createApi({
118117
merge: (currentCache, newItems) => {
119118
currentCache.push(...newItems)
120119
},
121-
forceRefetch: ({ currentArg, previousArg }) => {
120+
forceRefetch: () => {
122121
return true
123122
},
124123
}),
@@ -756,7 +755,7 @@ describe('hooks tests', () => {
756755
}
757756

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

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

19881988
const newPosts = posts.map((post, index) =>
19891989
index !== idx
19901990
? post
19911991
: {
1992-
...req.body,
1992+
...body,
19931993
id,
1994-
name: req.body.name || post.name,
1994+
name: body?.name || post.name,
19951995
fetched_at: new Date().toUTCString(),
19961996
}
19971997
)
19981998
posts = [...newPosts]
19991999

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

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

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

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

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { createApi } from '@reduxjs/toolkit/query'
22
import { actionsReducer, setupApiStore } from '../../tests/utils/helpers'
3-
import { delay } from '../../utils'
3+
import { delay } from 'msw'
44

55
const baseQuery = (args?: any) => ({ data: args })
66
const api = createApi({

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 '../../tests/utils/helpers'
4-
import { delay } from '../../utils'
55

66
let shouldApiResponseSuccess = true
77

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

Lines changed: 28 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -12,21 +12,14 @@ import type {
1212
} from '@reduxjs/toolkit/query'
1313
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
1414
import type { MockInstance } from 'vitest'
15-
import { vi } from 'vitest'
16-
17-
import { rest } from 'msw'
18-
import {
19-
ANY,
20-
getSerializedHeaders,
21-
setupApiStore,
22-
waitMs,
23-
} from '../../tests/utils/helpers'
24-
import { expectExactType, expectType } from '../../tests/utils/typeTestHelpers'
15+
2516
import type {
2617
DefinitionsFromApi,
2718
OverrideResultType,
2819
TagTypesFromApi,
2920
} from '@reduxjs/toolkit/dist/query/endpointDefinitions'
21+
import { HttpResponse, delay, http } from 'msw'
22+
import nodeFetch from 'node-fetch'
3023
import { server } from './mocks/server'
3124

3225
beforeAll(() => {
@@ -186,7 +179,7 @@ describe('wrong tagTypes log errors', () => {
186179
store.dispatch(api.endpoints[endpoint].initiate())
187180
let result: { status: string }
188181
do {
189-
await waitMs(5)
182+
await delay(5)
190183
// @ts-ignore
191184
result = api.endpoints[endpoint].select()(store.getState())
192185
} while (result.status === 'pending')
@@ -461,11 +454,11 @@ describe('endpoint definition typings', () => {
461454
})
462455

463456
storeRef.store.dispatch(api.endpoints.query1.initiate('in1'))
464-
await waitMs(1)
457+
await delay(1)
465458
expect(spy).not.toHaveBeenCalled()
466459

467460
storeRef.store.dispatch(api.endpoints.query2.initiate('in2'))
468-
await waitMs(1)
461+
await delay(1)
469462
expect(spy).toHaveBeenCalledWith(
470463
"Tag type 'missing' was used, but not specified in `tagTypes`!"
471464
)
@@ -652,11 +645,12 @@ describe('additional transformResponse behaviors', () => {
652645
query: build.query<SuccessResponse & EchoResponseData, void>({
653646
query: () => '/success',
654647
transformResponse: async (response: SuccessResponse) => {
655-
const res = await fetch('https://example.com/echo', {
648+
const res: any = await nodeFetch('https://example.com/echo', {
656649
method: 'POST',
657650
body: JSON.stringify({ banana: 'bread' }),
658651
}).then((res) => res.json())
659-
const additionalData = JSON.parse(res.body) as EchoResponseData
652+
653+
const additionalData = res.body as EchoResponseData
660654
return { ...response, ...additionalData }
661655
},
662656
}),
@@ -717,7 +711,6 @@ describe('additional transformResponse behaviors', () => {
717711
response: {
718712
headers: {
719713
'content-type': 'application/json',
720-
'x-powered-by': 'msw',
721714
},
722715
},
723716
},
@@ -738,7 +731,6 @@ describe('additional transformResponse behaviors', () => {
738731
response: {
739732
headers: {
740733
'content-type': 'application/json',
741-
'x-powered-by': 'msw',
742734
},
743735
},
744736
},
@@ -796,32 +788,36 @@ describe('query endpoint lifecycles - onStart, onSuccess, onError', () => {
796788
test('query lifecycle events fire properly', async () => {
797789
// We intentionally fail the first request so we can test all lifecycles
798790
server.use(
799-
rest.get('https://example.com/success', (_, res, ctx) =>
800-
res.once(ctx.status(500), ctx.json({ value: 'failed' }))
791+
http.get(
792+
'https://example.com/success',
793+
() => HttpResponse.json({ value: 'failed' }, { status: 500 }),
794+
{ once: true }
801795
)
802796
)
803797

804798
expect(storeRef.store.getState().testReducer.count).toBe(null)
805799
const failAttempt = storeRef.store.dispatch(api.endpoints.query.initiate())
806800
expect(storeRef.store.getState().testReducer.count).toBe(0)
807801
await failAttempt
808-
await waitMs(10)
802+
await delay(10)
809803
expect(storeRef.store.getState().testReducer.count).toBe(-1)
810804

811805
const successAttempt = storeRef.store.dispatch(
812806
api.endpoints.query.initiate()
813807
)
814808
expect(storeRef.store.getState().testReducer.count).toBe(0)
815809
await successAttempt
816-
await waitMs(10)
810+
await delay(10)
817811
expect(storeRef.store.getState().testReducer.count).toBe(1)
818812
})
819813

820814
test('mutation lifecycle events fire properly', async () => {
821815
// We intentionally fail the first request so we can test all lifecycles
822816
server.use(
823-
rest.post('https://example.com/success', (_, res, ctx) =>
824-
res.once(ctx.status(500), ctx.json({ value: 'failed' }))
817+
http.post(
818+
'https://example.com/success',
819+
() => HttpResponse.json({ value: 'failed' }, { status: 500 }),
820+
{ once: true }
825821
)
826822
)
827823

@@ -945,7 +941,7 @@ describe('custom serializeQueryArgs per endpoint', () => {
945941
}
946942

947943
const dummyClient: MyApiClient = {
948-
async fetchPost(id) {
944+
async fetchPost() {
949945
return { value: 'success' }
950946
},
951947
}
@@ -1106,12 +1102,13 @@ describe('custom serializeQueryArgs per endpoint', () => {
11061102
const PAGE_SIZE = 3
11071103

11081104
server.use(
1109-
rest.get('https://example.com/listItems', (req, res, ctx) => {
1110-
const pageString = req.url.searchParams.get('page')
1105+
http.get('https://example.com/listItems', ({ request }) => {
1106+
const url = new URL(request.url)
1107+
const pageString = url.searchParams.get('page')
11111108
const pageNum = parseInt(pageString || '0')
11121109

11131110
const results = paginate(allItems, PAGE_SIZE, pageNum)
1114-
return res(ctx.json(results))
1111+
return HttpResponse.json(results)
11151112
})
11161113
)
11171114

@@ -1134,12 +1131,13 @@ describe('custom serializeQueryArgs per endpoint', () => {
11341131
const PAGE_SIZE = 3
11351132

11361133
server.use(
1137-
rest.get('https://example.com/listItems2', (req, res, ctx) => {
1138-
const pageString = req.url.searchParams.get('page')
1134+
http.get('https://example.com/listItems2', ({ request }) => {
1135+
const url = new URL(request.url)
1136+
const pageString = url.searchParams.get('page')
11391137
const pageNum = parseInt(pageString || '0')
11401138

11411139
const results = paginate(allItems, PAGE_SIZE, pageNum)
1142-
return res(ctx.json(results))
1140+
return HttpResponse.json(results)
11431141
})
11441142
)
11451143

0 commit comments

Comments
 (0)