[web] Update fetch-mock to version 12 (#24837)

* Update fetch-mock to version 12

* Replace `fetchMock.done` by `fetchMock.callHistory.done`

* Replace `…Mock.called` by `…Mock.callHistory.called`

* Replace `fetchMock.reset` by `fetchMock.hardReset`

* Replace `fetchMock.restore` by `fetchMock.hardReset`

* Replace `fetchMock.resetHistory` by `fetchMock.clearHistory`

* Replace `fetchMock.calls` by `fetchMock.callHistory.calls`

* Replace `fetchMock.flush` by `fetchMock.callHistory.flush`

* Update tests for fetch-mock version 12

See https://www.wheresrhys.co.uk/fetch-mock/docs/Usage/upgrade-guide

* Update stories for fetch-mock version 12

* Remove `overwriteRoutes` option

* Add `fetchMock.spyGlobal()` to storybook

* Remove deprecated `sendAsJson` param

* Replace `fetchMock.hardReset()` by `fetchMock.removeRoutes().clearHistory()`

* Fixup fetch-mock in storybook:

Call `mockGlobal` inside the hook, call `removeRoutes` and `unmockGlobal` on cleanup

Behaviour can be tested by navigating between

https://storybook.dev-overleaf.com/main/?path=/story/editor-ai-error-assistant-compile-log-entries--first-log-entry
https://storybook.dev-overleaf.com/main/?path=/story/editor-ai-error-assistant-compile-log-entries--rate-limited

https://storybook.dev-overleaf.com/main/?path=/story/project-list-notifications--project-invite
https://storybook.dev-overleaf.com/main/?path=/story/project-list-notifications--project-invite-network-error

And clicking the buttons

GitOrigin-RevId: 35611b4430259e4c21c3d819ad18b2e6dab66242
This commit is contained in:
Antoine Clausse
2025-04-17 08:06:24 +00:00
committed by Copybot
parent fa62529d82
commit b901bb6c75
99 changed files with 728 additions and 729 deletions
@@ -29,7 +29,7 @@ describe('<AccountInfoSection />', function () {
})
afterEach(function () {
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
})
it('submits all inputs', async function () {
@@ -50,14 +50,14 @@ describe('<AccountInfoSection />', function () {
name: 'Update',
})
)
expect(updateMock.called()).to.be.true
expect(JSON.parse(updateMock.lastCall()![1]!.body as string)).to.deep.equal(
{
email: 'john@watson.co.uk',
first_name: 'John',
last_name: 'Watson',
}
)
expect(updateMock.callHistory.called()).to.be.true
expect(
JSON.parse(updateMock.callHistory.calls().at(-1)?.options.body as string)
).to.deep.equal({
email: 'john@watson.co.uk',
first_name: 'John',
last_name: 'Watson',
})
})
it('disables button on invalid email', async function () {
@@ -74,7 +74,7 @@ describe('<AccountInfoSection />', function () {
expect(button.disabled).to.be.true
fireEvent.click(button)
expect(updateMock.called()).to.be.false
expect(updateMock.callHistory.called()).to.be.false
})
it('shows inflight state and success message', async function () {
@@ -156,12 +156,12 @@ describe('<AccountInfoSection />', function () {
name: 'Update',
})
)
expect(JSON.parse(updateMock.lastCall()![1]!.body as string)).to.deep.equal(
{
first_name: 'Sherlock',
last_name: 'Holmes',
}
)
expect(
JSON.parse(updateMock.callHistory.calls().at(-1)?.options.body as string)
).to.deep.equal({
first_name: 'Sherlock',
last_name: 'Holmes',
})
})
it('disables email input', async function () {
@@ -187,12 +187,12 @@ describe('<AccountInfoSection />', function () {
name: 'Update',
})
)
expect(JSON.parse(updateMock.lastCall()![1]!.body as string)).to.deep.equal(
{
first_name: 'Sherlock',
last_name: 'Holmes',
}
)
expect(
JSON.parse(updateMock.callHistory.calls().at(-1)?.options.body as string)
).to.deep.equal({
first_name: 'Sherlock',
last_name: 'Holmes',
})
})
it('disables names input', async function () {
@@ -215,10 +215,10 @@ describe('<AccountInfoSection />', function () {
name: 'Update',
})
)
expect(JSON.parse(updateMock.lastCall()![1]!.body as string)).to.deep.equal(
{
email: 'sherlock@holmes.co.uk',
}
)
expect(
JSON.parse(updateMock.callHistory.calls().at(-1)?.options.body as string)
).to.deep.equal({
email: 'sherlock@holmes.co.uk',
})
})
})
@@ -19,7 +19,7 @@ describe('<AddEmailInput/>', function () {
beforeEach(function () {
clearDomainCache()
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
})
describe('on initial render', function () {
@@ -69,7 +69,7 @@ describe('<AddEmailInput/>', function () {
})
it('should not make any request for institution domains', function () {
expect(fetchMock.called()).to.be.false
expect(fetchMock.callHistory.called()).to.be.false
})
it('should submit on Enter if email looks valid', async function () {
@@ -118,11 +118,18 @@ describe('<AddEmailInput/>', function () {
})
describe('when there is a domain match', function () {
beforeEach(function () {
beforeEach(async function () {
fetchMock.get('express:/institutions/domains', testInstitutionData)
fireEvent.change(screen.getByTestId('affiliations-email'), {
target: { value: 'user@d' },
})
// Wait for component to process the change and update the shadow input
await waitFor(() => {
const shadowInput = screen.getByTestId(
'affiliations-email-shadow'
) as HTMLInputElement
expect(shadowInput.value).to.equal('user@domain.edu')
})
})
it('should render the text being typed along with the suggestion', async function () {
@@ -146,7 +153,7 @@ describe('<AddEmailInput/>', function () {
fireEvent.change(screen.getByTestId('affiliations-email'), {
target: { value: 'user@domain.edu' },
})
await fetchMock.flush(true)
await fetchMock.callHistory.flush(true)
expect(
onChangeStub.calledWith(
'user@domain.edu',
@@ -231,7 +238,7 @@ describe('<AddEmailInput/>', function () {
})
it('should cache the result and skip subsequent requests', async function () {
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
// clear input
fireEvent.change(screen.getByTestId('affiliations-email'), {
@@ -242,7 +249,7 @@ describe('<AddEmailInput/>', function () {
target: { value: 'user@d' },
})
expect(fetchMock.called()).to.be.false
expect(fetchMock.callHistory.called()).to.be.false
expect(onChangeStub.calledWith('user@d')).to.equal(true)
await waitFor(() => {
const shadowInput = screen.getByTestId(
@@ -258,7 +265,7 @@ describe('<AddEmailInput/>', function () {
afterEach(function () {
clearDomainCache()
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
})
it('should not render the suggestion with blocked domain', async function () {
@@ -269,7 +276,7 @@ describe('<AddEmailInput/>', function () {
fireEvent.change(screen.getByTestId('affiliations-email'), {
target: { value: `user@${blockedDomain.split('.')[0]}` },
})
await fetchMock.flush(true)
await fetchMock.callHistory.flush(true)
expect(screen.queryByText(`user@${blockedDomain}`)).to.be.null
})
@@ -286,7 +293,7 @@ describe('<AddEmailInput/>', function () {
value: `user@subdomain.${blockedDomain.split('.')[0]}`,
},
})
await fetchMock.flush(true)
await fetchMock.callHistory.flush(true)
expect(screen.queryByText(`user@subdomain.${blockedDomain}`)).to.be.null
})
})
@@ -307,7 +314,7 @@ describe('<AddEmailInput/>', function () {
// make sure the next suggestions are delayed
clearDomainCache()
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
fetchMock.get('express:/institutions/domains', 200, { delay: 1000 })
})
@@ -354,7 +361,7 @@ describe('<AddEmailInput/>', function () {
})
// subsequent requests fail
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
fetchMock.get('express:/institutions/domains', 500)
})
@@ -373,7 +380,7 @@ describe('<AddEmailInput/>', function () {
expect(shadowInput.value).to.equal('')
})
expect(fetchMock.called()).to.be.true // ensures `domainCache` hasn't been hit
expect(fetchMock.callHistory.called()).to.be.true // ensures `domainCache` hasn't been hit
})
})
@@ -384,7 +391,7 @@ describe('<AddEmailInput/>', function () {
fireEvent.change(screen.getByTestId('affiliations-email'), {
target: { value: 'user@other' },
})
await fetchMock.flush(true)
await fetchMock.callHistory.flush(true)
const shadowInput = screen.getByTestId(
'affiliations-email-shadow'
) as HTMLInputElement
@@ -37,7 +37,7 @@ describe('<EmailsRow/>', function () {
})
afterEach(function () {
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
})
describe('with unaffiliated email data', function () {
@@ -86,9 +86,9 @@ describe('<EmailsRow/>', function () {
describe('when the email is not yet linked to the institution', function () {
beforeEach(async function () {
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
fetchMock.get(/\/user\/emails/, [affiliatedEmail, unconfirmedUserData])
await fetchMock.flush(true)
await fetchMock.callHistory.flush(true)
})
it('prompts the user to link to their institutional account', function () {
@@ -103,9 +103,9 @@ describe('<EmailsRow/>', function () {
describe('when the email is already linked to the institution', function () {
beforeEach(async function () {
affiliatedEmail.samlProviderId = '1'
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
fetchMock.get(/\/user\/emails/, [affiliatedEmail, unconfirmedUserData])
await fetchMock.flush(true)
await fetchMock.callHistory.flush(true)
})
it('prompts the user to login using their institutional account', function () {
@@ -37,11 +37,11 @@ describe('email actions - make primary', function () {
Object.assign(getMeta('ol-ExposedSettings'), {
hasAffiliationsFeature: true,
})
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
})
afterEach(function () {
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
})
describe('disabled `make primary` button', function () {
@@ -236,11 +236,11 @@ describe('email actions - delete', function () {
Object.assign(getMeta('ol-ExposedSettings'), {
hasAffiliationsFeature: true,
})
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
})
afterEach(function () {
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
})
it('shows loader when deleting and removes the row', async function () {
@@ -56,7 +56,7 @@ const institutionDomainData = [
] as const
function resetFetchMock() {
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
fetchMock.get('express:/institutions/domains', [])
}
@@ -80,7 +80,7 @@ describe('<EmailsSection />', function () {
hasSamlFeature: true,
samlInitPath: 'saml/init',
})
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
})
afterEach(function () {
@@ -97,7 +97,7 @@ describe('<EmailsSection />', function () {
it('renders input', async function () {
fetchMock.get('/user/emails?ensureAffiliation=true', [])
render(<EmailsSection />)
await fetchMock.flush(true)
await fetchMock.callHistory.flush(true)
const button = await screen.findByRole<HTMLButtonElement>('button', {
name: /add another email/i,
@@ -112,7 +112,7 @@ describe('<EmailsSection />', function () {
fetchMock.get(`/institutions/domains?hostname=email.com&limit=1`, 200)
fetchMock.get(`/institutions/domains?hostname=email&limit=1`, 200)
render(<EmailsSection />)
await fetchMock.flush(true)
await fetchMock.callHistory.flush(true)
const button = await screen.findByRole<HTMLButtonElement>('button', {
name: /add another email/i,
@@ -190,7 +190,7 @@ describe('<EmailsSection />', function () {
{ name: /add another email/i }
)
await fetchMock.flush(true)
await fetchMock.callHistory.flush(true)
resetFetchMock()
fetchMock
.get('/user/emails?ensureAffiliation=true', [userEmailData])
@@ -233,7 +233,7 @@ describe('<EmailsSection />', function () {
{ name: /add another email/i }
)
await fetchMock.flush(true)
await fetchMock.callHistory.flush(true)
resetFetchMock()
fetchMock
.get('/user/emails?ensureAffiliation=true', [])
@@ -271,8 +271,8 @@ describe('<EmailsSection />', function () {
name: /add another email/i,
})
await fetchMock.flush(true)
fetchMock.reset()
await fetchMock.callHistory.flush(true)
fetchMock.removeRoutes().clearHistory()
fetchMock.get('express:/institutions/domains', institutionDomainData)
await userEvent.click(button)
@@ -295,7 +295,7 @@ describe('<EmailsSection />', function () {
name: /add another email/i,
})
await fetchMock.flush(true)
await fetchMock.callHistory.flush(true)
resetFetchMock()
await userEvent.click(button)
@@ -330,7 +330,7 @@ describe('<EmailsSection />', function () {
expect(universityInput.disabled).to.be.false
await fetchMock.flush(true)
await fetchMock.callHistory.flush(true)
resetFetchMock()
// Select the university from dropdown
@@ -364,9 +364,11 @@ describe('<EmailsSection />', function () {
})
)
const [[, request]] = fetchMock.calls(/\/user\/emails/)
const request = fetchMock.callHistory.calls(/\/user\/emails/).at(0)
expect(JSON.parse(request?.body?.toString() || '{}')).to.deep.include({
expect(
JSON.parse(request?.options.body?.toString() || '{}')
).to.deep.include({
email: userEmailData.email,
university: {
id: userEmailData.affiliation?.institution.id,
@@ -393,7 +395,7 @@ describe('<EmailsSection />', function () {
name: /add another email/i,
})
await fetchMock.flush(true)
await fetchMock.callHistory.flush(true)
resetFetchMock()
fetchMock.get('/institutions/list?country_code=de', [
@@ -446,7 +448,7 @@ describe('<EmailsSection />', function () {
name: /add another email/i,
})
await fetchMock.flush(true)
await fetchMock.callHistory.flush(true)
resetFetchMock()
await userEvent.click(button)
@@ -481,7 +483,7 @@ describe('<EmailsSection />', function () {
expect(universityInput.disabled).to.be.false
await fetchMock.flush(true)
await fetchMock.callHistory.flush(true)
resetFetchMock()
// Enter the university manually
@@ -516,9 +518,11 @@ describe('<EmailsSection />', function () {
await confirmCodeForEmail(userEmailData.email)
const [[, request]] = fetchMock.calls(/\/user\/emails/)
const request = fetchMock.callHistory.calls(/\/user\/emails/).at(0)
expect(JSON.parse(request?.body?.toString() || '{}')).to.deep.include({
expect(
JSON.parse(request?.options.body?.toString() || '{}')
).to.deep.include({
email: userEmailData.email,
university: {
name: newUniversity,
@@ -554,8 +558,8 @@ describe('<EmailsSection />', function () {
name: /add another email/i,
})
await fetchMock.flush(true)
fetchMock.reset()
await fetchMock.callHistory.flush(true)
fetchMock.removeRoutes().clearHistory()
fetchMock.get(
`/institutions/domains?hostname=${hostnameFirstChar}&limit=1`,
institutionDomainDataCopy
@@ -569,8 +573,8 @@ describe('<EmailsSection />', function () {
)
await userEvent.keyboard('{Tab}')
await fetchMock.flush(true)
fetchMock.reset()
await fetchMock.callHistory.flush(true)
fetchMock.removeRoutes().clearHistory()
expect(
screen.queryByRole('textbox', {
@@ -627,8 +631,8 @@ describe('<EmailsSection />', function () {
name: /add another email/i,
})
await fetchMock.flush(true)
fetchMock.reset()
await fetchMock.callHistory.flush(true)
fetchMock.removeRoutes().clearHistory()
fetchMock.get(
`/institutions/domains?hostname=${hostnameFirstChar}&limit=1`,
institutionDomainDataCopy
@@ -642,8 +646,8 @@ describe('<EmailsSection />', function () {
)
await userEvent.keyboard('{Tab}')
await fetchMock.flush(true)
fetchMock.reset()
await fetchMock.callHistory.flush(true)
fetchMock.removeRoutes().clearHistory()
screen.getByText(institutionDomainDataCopy[0].university.name)
@@ -679,8 +683,8 @@ describe('<EmailsSection />', function () {
await confirmCodeForEmail('user@autocomplete.edu')
await fetchMock.flush(true)
fetchMock.reset()
await fetchMock.callHistory.flush(true)
fetchMock.removeRoutes().clearHistory()
screen.getByText(userEmailDataCopy.affiliation.institution.name, {
exact: false,
@@ -79,12 +79,14 @@ describe('user role and institution', function () {
Object.assign(getMeta('ol-ExposedSettings'), {
hasAffiliationsFeature: true,
})
fetchMock.reset()
fetchMock.get('/user/emails?ensureAffiliation=true', [])
fetchMock.removeRoutes().clearHistory()
fetchMock.get('/user/emails?ensureAffiliation=true', [], {
name: 'get user emails',
})
})
afterEach(function () {
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
})
it('renders affiliation name with add role/department button', function () {
@@ -122,13 +124,11 @@ describe('user role and institution', function () {
it('fetches institution data and replaces departments dropdown on add/change', async function () {
const userEmailData = userData1
fetchMock.get('/user/emails?ensureAffiliation=true', [userEmailData], {
overwriteRoutes: true,
})
fetchMock.modifyRoute('get user emails', { response: [userEmailData] })
render(<EmailsSection />)
await fetchMock.flush(true)
fetchMock.reset()
await fetchMock.callHistory.flush(true)
fetchMock.removeRoutes().clearHistory()
const fakeDepartment = 'Fake department'
const institution = userEmailData.affiliation.institution
@@ -143,8 +143,8 @@ describe('user role and institution', function () {
screen.getByRole('button', { name: /add role and department/i })
)
await fetchMock.flush(true)
fetchMock.reset()
await fetchMock.callHistory.flush(true)
fetchMock.removeRoutes().clearHistory()
fireEvent.click(screen.getByRole('textbox', { name: /department/i }))
@@ -153,9 +153,7 @@ describe('user role and institution', function () {
it('adds new role and department', async function () {
fetchMock
.get('/user/emails?ensureAffiliation=true', [userData1], {
overwriteRoutes: true,
})
.modifyRoute('get user emails', { response: [userData1] })
.get(/\/institutions\/list/, { departments: [] })
.post('/user/emails/endorse', 200)
render(<EmailsSection />)
@@ -22,11 +22,11 @@ describe('<EmailsSection />', function () {
Object.assign(getMeta('ol-ExposedSettings'), {
hasAffiliationsFeature: true,
})
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
})
afterEach(function () {
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
})
it('renders translated heading', function () {
@@ -42,7 +42,7 @@ describe('<ReconfirmationInfo/>', function () {
})
afterEach(function () {
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
this.locationStub.restore()
})
@@ -145,13 +145,13 @@ describe('<ReconfirmationInfo/>', function () {
await waitFor(() => {
expect(confirmButton.disabled).to.be.true
})
expect(fetchMock.called()).to.be.true
expect(fetchMock.callHistory.called()).to.be.true
// the confirmation text should now be displayed
await screen.findByText(/Please check your email inbox to confirm/)
// try the resend button
fetchMock.resetHistory()
fetchMock.clearHistory()
const resendButton = await screen.findByRole('button', {
name: 'Resend confirmation email',
})
@@ -160,7 +160,7 @@ describe('<ReconfirmationInfo/>', function () {
// commented out as it's already gone by this point
// await screen.findByText(/Sending/)
expect(fetchMock.called()).to.be.true
expect(fetchMock.callHistory.called()).to.be.true
await waitForElementToBeRemoved(() => screen.getByText('Sending…'))
await screen.findByRole('button', {
name: 'Resend confirmation email',
@@ -12,7 +12,7 @@ describe('<LeaveModalContent />', function () {
})
afterEach(function () {
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
})
it('disable delete button if form is not valid', function () {
@@ -1,7 +1,7 @@
import { expect } from 'chai'
import sinon from 'sinon'
import { fireEvent, screen, render, waitFor } from '@testing-library/react'
import fetchMock, { FetchMockStatic } from 'fetch-mock'
import fetchMock, { type FetchMock } from 'fetch-mock'
import LeaveModalForm from '../../../../../../frontend/js/features/settings/components/leave/modal-form'
import * as useLocationModule from '../../../../../../frontend/js/shared/hooks/use-location'
@@ -14,7 +14,7 @@ describe('<LeaveModalForm />', function () {
})
afterEach(function () {
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
})
it('validates form', async function () {
@@ -50,7 +50,7 @@ describe('<LeaveModalForm />', function () {
describe('submits', async function () {
let setInFlight: sinon.SinonStub
let setIsFormValid: sinon.SinonStub
let deleteMock: FetchMockStatic
let deleteMock: FetchMock
let assignStub: sinon.SinonStub
beforeEach(function () {
@@ -68,7 +68,7 @@ describe('<LeaveModalForm />', function () {
})
afterEach(function () {
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
this.locationStub.restore()
})
@@ -85,7 +85,7 @@ describe('<LeaveModalForm />', function () {
sinon.assert.calledOnce(setInFlight)
sinon.assert.calledWithMatch(setInFlight, true)
expect(deleteMock.called()).to.be.true
expect(deleteMock.callHistory.called()).to.be.true
await waitFor(() => {
sinon.assert.calledTwice(setInFlight)
sinon.assert.calledWithMatch(setInFlight, false)
@@ -105,7 +105,7 @@ describe('<LeaveModalForm />', function () {
fireEvent.submit(screen.getByLabelText('Email'))
expect(deleteMock.called()).to.be.false
expect(deleteMock.callHistory.called()).to.be.false
sinon.assert.notCalled(setInFlight)
})
})
@@ -13,7 +13,7 @@ describe('<LeaveModal />', function () {
})
afterEach(function () {
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
})
it('closes modal on cancel', async function () {
@@ -21,7 +21,7 @@ describe('<LeaversSurveyAlert/>', function () {
})
afterEach(function () {
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
})
it('should render before the expiration date', function () {
@@ -52,7 +52,7 @@ describe('<LinkingSection />', function () {
})
afterEach(function () {
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
})
it('shows header', async function () {
@@ -17,7 +17,7 @@ describe('<PasswordSection />', function () {
})
afterEach(function () {
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
})
it('shows password managed externally message', async function () {
@@ -45,14 +45,14 @@ describe('<PasswordSection />', function () {
render(<PasswordSection />)
submitValidForm()
expect(updateMock.called()).to.be.true
expect(JSON.parse(updateMock.lastCall()![1]!.body as string)).to.deep.equal(
{
currentPassword: 'foobar',
newPassword1: 'barbaz',
newPassword2: 'barbaz',
}
)
expect(updateMock.callHistory.called()).to.be.true
expect(
JSON.parse(updateMock.callHistory.calls().at(-1)?.options.body as string)
).to.deep.equal({
currentPassword: 'foobar',
newPassword1: 'barbaz',
newPassword2: 'barbaz',
})
})
it('disables button on invalid form', async function () {
@@ -64,7 +64,7 @@ describe('<PasswordSection />', function () {
name: 'Change',
})
)
expect(updateMock.called()).to.be.false
expect(updateMock.callHistory.called()).to.be.false
})
it('validates inputs', async function () {
@@ -5,7 +5,7 @@ import fetchMock from 'fetch-mock'
describe('<SecuritySection />', function () {
afterEach(function () {
fetchMock.reset()
fetchMock.removeRoutes().clearHistory()
})
it('shows Group SSO rows in security section', async function () {