Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion examples/query/react/basic/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
"react-scripts": "5.0.1"
},
"devDependencies": {
"@testing-library/react": "^13.3.0",
"@testing-library/dom": "^10.4.0",
"@testing-library/react": "^16.0.1",
Comment on lines -16 to +17
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Honestly, I didn’t get how to run tests in examples, and how to check if everything is OK.

When I run yarn test in the master branch, the tests run only for the following packages:

  • @reduxjs/rtk-codemods
  • @rtk-query/codegen-openapi
  • @rtk-query/graphql-request-base-query
  • @reduxjs/toolkit

And when I go to examples/query/react/basic and run npm test there, I get the following error:

> @examples-query-react/[email protected] test
> react-scripts test --runInBand

TypeError: Cannot read properties of undefined (reading 'EXTENSION')
    at Runtime.createHasteMap (rtk/node_modules/jest-runtime/build/index.js:547:43)
    at rtk/node_modules/@jest/core/build/cli/index.js:231:55
    at Array.map (<anonymous>)
    at buildContextsAndHasteMaps (rtk/node_modules/@jest/core/build/cli/index.js:228:13)
    at _run10000 (rtk/node_modules/@jest/core/build/cli/index.js:305:47)
    at runCLI (rtk/node_modules/@jest/core/build/cli/index.js:173:9)
    at async Object.run (rtk/node_modules/jest-cli/build/cli/index.js:155:37)
npm error Lifecycle script `test` failed with error:
npm error code 1
npm error path rtk/examples/query/react/basic
npm error workspace @examples-query-react/[email protected]
npm error location rtk/examples/query/react/basic
npm error command failed
npm error command sh -c react-scripts test --runInBand

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That should be fixed by #4603.

Copy link
Contributor Author

@isqua isqua Nov 2, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should I correct something in this regard in the current pull request? Do you wanna merge #4603 first?

"@types/jest": "^26.0.23",
"@types/react": "^18.0.5",
"@types/react-dom": "^18.0.5",
Expand Down
3 changes: 2 additions & 1 deletion examples/query/react/kitchen-sink/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@
"react-scripts": "5.0.1"
},
"devDependencies": {
"@testing-library/dom": "^10.4.0",
"@testing-library/jest-dom": "^5.11.5",
"@testing-library/react": "^13.3.0",
"@testing-library/react": "^16.0.1",
"@types/jest": "^26.0.23",
"@types/node": "^14.14.6",
"@types/react": "^18.0.5",
Expand Down
5 changes: 3 additions & 2 deletions packages/toolkit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,9 @@
"@phryneas/ts-version": "^1.0.2",
"@size-limit/file": "^11.0.1",
"@size-limit/webpack": "^11.0.1",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^13.1.5",
"@testing-library/dom": "^10.4.0",
"@testing-library/react": "^16.0.1",
"@testing-library/user-event": "^14.5.2",
Comment on lines -59 to +61
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated @testing-library/react to the latest version.
Changelogs for major updates: v14.0.0, v15.0.0, v16.0.0.

Since the version v16.0.0, @testing-library/dom was moved to a peer dependency, so we need to explicitly install it.

Updated @testing-library/user-event to the latest version. Major changes: v14.0.0

"@types/babel__core": "^7.20.5",
"@types/babel__helper-module-imports": "^7.18.3",
"@types/json-stringify-safe": "^5.0.0",
Expand Down
6 changes: 6 additions & 0 deletions packages/toolkit/src/query/tests/apiProvider.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ const api = createApi({
}),
})

afterEach(() => {
vi.resetAllMocks()
})

describe('ApiProvider', () => {
test('ApiProvider allows a user to make queries without a traditional Redux setup', async () => {
function User() {
Expand Down Expand Up @@ -72,6 +76,8 @@ describe('ApiProvider', () => {
expect(getByTestId('isFetching').textContent).toBe('false')
})
test('ApiProvider throws if nested inside a Redux context', () => {
// Intentionally swallow the "unhandled error" message
vi.spyOn(console, 'error').mockImplementation(() => {})
expect(() =>
render(
<Provider store={configureStore({ reducer: () => null })}>
Expand Down
31 changes: 21 additions & 10 deletions packages/toolkit/src/query/tests/buildHooks.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
actionsReducer,
setupApiStore,
useRenderCounter,
waitForFakeTimer,
waitMs,
withProvider,
} from '@internal/tests/utils/helpers'
Expand Down Expand Up @@ -47,7 +48,7 @@ interface Item {

const api = createApi({
baseQuery: async (arg: any) => {
await waitMs(150)
await waitForFakeTimer(150)
if (arg?.body && 'amount' in arg.body) {
amount += 1
}
Expand Down Expand Up @@ -465,7 +466,6 @@ describe('hooks tests', () => {
<div>
<button
onClick={() => {
console.log('Refetching')
refetch()
}}
>
Expand Down Expand Up @@ -915,7 +915,7 @@ describe('hooks tests', () => {
resPromise = refetch()
})
expect(resPromise).toBeInstanceOf(Promise)
const res = await resPromise
const res = await act(() => resPromise)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed this warning:

Warning: An update to TestComponent inside a test was not wrapped in act(...).

When testing, code that causes React state updates should be wrapped into act(...):

act(() => {
  /* fire events that update state */
});
/* assert on the output */

This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act
    at TestComponent (redux-toolkit/node_modules/@testing-library/react/dist/pure.js:307:5)
    at Provider (redux-toolkit/node_modules/react-redux/dist/react-redux.mjs:1036:3)
    at Wrapper (redux-toolkit/packages/toolkit/src/tests/utils/helpers.tsx:39:29)

expect(res.data!.amount).toBeGreaterThan(originalAmount)
})

Expand Down Expand Up @@ -1095,15 +1095,15 @@ describe('hooks tests', () => {
// Allow at least three state effects to hit.
// Trying to see if any [true, false, true] occurs.
await act(async () => {
await waitMs(1)
await waitForFakeTimer(150)
})

await act(async () => {
await waitMs(1)
await waitForFakeTimer(150)
})

await act(async () => {
await waitMs(1)
await waitForFakeTimer(150)
})

// Find if at any time the isLoading state has reverted
Expand Down Expand Up @@ -1864,7 +1864,8 @@ describe('hooks tests', () => {
expect(screen.getByTestId('isFetching').textContent).toBe('false'),
)

userEvent.hover(screen.getByTestId('highPriority'))
await userEvent.hover(screen.getByTestId('highPriority'))
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since Release v14.0.0 · testing-library/user-event userEvent.hover returns a promise, so we need to await here.


expect(
api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any),
).toEqual({
Expand Down Expand Up @@ -2001,7 +2002,7 @@ describe('hooks tests', () => {
await waitMs(400)

// This should run the query being that we're past the threshold
userEvent.hover(screen.getByTestId('lowPriority'))
await userEvent.hover(screen.getByTestId('lowPriority'))
expect(
api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any),
).toEqual({
Expand Down Expand Up @@ -2101,7 +2102,7 @@ describe('hooks tests', () => {

render(<User />, { wrapper: storeRef.wrapper })

userEvent.hover(screen.getByTestId('lowPriority'))
await userEvent.hover(screen.getByTestId('lowPriority'))

expect(
api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any),
Expand Down Expand Up @@ -2993,6 +2994,11 @@ describe('skip behavior', () => {
await act(async () => {
rerender([1])
})

await act(async () => {
await waitForFakeTimer(150)
})

expect(result.current).toMatchObject({ status: QueryStatus.fulfilled })
await waitMs(1)
expect(getSubscriptionCount('getUser(1)')).toBe(1)
Expand Down Expand Up @@ -3030,6 +3036,11 @@ describe('skip behavior', () => {
await act(async () => {
rerender([1])
})

await act(async () => {
await waitForFakeTimer(150)
})

expect(result.current).toMatchObject({ status: QueryStatus.fulfilled })
await waitMs(1)
expect(getSubscriptionCount('getUser(1)')).toBe(1)
Expand Down Expand Up @@ -3059,7 +3070,7 @@ describe('skip behavior', () => {
)

await act(async () => {
await waitMs(1)
await waitForFakeTimer(150)
})

// Normal fulfilled result, with both `data` and `currentData`
Expand Down
2 changes: 1 addition & 1 deletion packages/toolkit/src/query/tests/cleanup.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ function UsingAB() {
}

beforeAll(() => {
vi.useFakeTimers()
vi.useFakeTimers({ shouldAdvanceTime: true })
})

test('data stays in store when component stays rendered', async () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/toolkit/src/query/tests/fetchBaseQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -862,7 +862,7 @@ describe('fetchBaseQuery', () => {
prepare.apply(undefined, arguments as unknown as any[])
},
})
baseQuery('http://example.com', commonBaseQueryApi, {
baseQuery('https://example.com', commonBaseQueryApi, {
foo: 'baz',
bar: 5,
})
Expand Down
6 changes: 6 additions & 0 deletions packages/toolkit/src/query/tests/mocks/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ export const posts: Record<string, Post> = {
}

export const handlers = [
http.get(
'https://example.com',
async ({ request, params, cookies, requestId }) => {
HttpResponse.json({ value: 'success' })
},
),
http.get(
'https://example.com/echo',
async ({ request, params, cookies, requestId }) => {
Expand Down
37 changes: 22 additions & 15 deletions packages/toolkit/src/query/tests/optimisticUpserts.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -399,27 +399,34 @@ describe('upsertQueryEntries', () => {
storeRef.store.dispatch(entriesAction)

// Tricky timing. The cache data promises will be resolved
// in microtasks, so we just need any async delay here.
await delay(1)
// in microtasks. We need to wait for them. Best to do this
// in a loop just to avoid a hardcoded delay, but also this
// needs to complete before `keepUnusedDataFor` expires them.
await waitFor(
() => {
const state = storeRef.store.getState()

// onCacheEntryAdded should have run for each post,
// including cache data being resolved
for (const post of posts) {
const matchingSideEffectAction = state.actions.find(
(action) =>
postAddedAction.match(action) && action.payload === post.id,
)
expect(matchingSideEffectAction).toBeTruthy()
}

const state = storeRef.store.getState()
const selectedData =
api.endpoints.postWithSideEffect.select('1')(state).data

// onCacheEntryAdded should have run for each post,
// including cache data being resolved
for (const post of posts) {
const matchingSideEffectAction = state.actions.find(
(action) => postAddedAction.match(action) && action.payload === post.id,
)
expect(matchingSideEffectAction).toBeTruthy()
}

expect(api.endpoints.postWithSideEffect.select('1')(state).data).toBe(
posts[0],
expect(selectedData).toBe(posts[0])
},
{ timeout: 50, interval: 5 },
)

// The cache data should be removed after the keepUnusedDataFor time,
// so wait longer than that
await delay(20)
await delay(100)

const stateAfter = storeRef.store.getState()

Expand Down
18 changes: 6 additions & 12 deletions packages/toolkit/src/query/tests/refetchingBehaviors.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,12 @@ describe('refetchOnFocus tests', () => {
expect(screen.getByTestId('amount').textContent).toBe('1'),
)

fireEvent.focus(window)

await act(async () => {
fireEvent.focus(window)
await delay(150)
})

await delay(150)

await waitFor(() =>
expect(screen.getByTestId('amount').textContent).toBe('2'),
)
Expand Down Expand Up @@ -111,9 +111,7 @@ describe('refetchOnFocus tests', () => {
expect(screen.getByTestId('amount').textContent).toBe('1'),
)

act(() => {
fireEvent.focus(window)
})
fireEvent.focus(window)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fireEvent is already wrapped in the act function: Common mistakes with React Testing Library


await delay(150)

Expand Down Expand Up @@ -165,9 +163,7 @@ describe('refetchOnFocus tests', () => {
expect(screen.getByTestId('amount').textContent).toBe('1'),
)

act(() => {
fireEvent.focus(window)
})
fireEvent.focus(window)
expect(screen.getByTestId('isLoading').textContent).toBe('false')
await waitFor(() =>
expect(screen.getByTestId('isFetching').textContent).toBe('true'),
Expand Down Expand Up @@ -213,9 +209,7 @@ describe('refetchOnFocus tests', () => {

expect(getIncrementedAmountState()).not.toBeUndefined()

await act(async () => {
fireEvent.focus(window)
})
fireEvent.focus(window)

await delay(1)
expect(getIncrementedAmountState()).toBeUndefined()
Expand Down
Loading