Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(setupServer): reapply interception after calling server.listen() after server.close() #2383

Merged
merged 2 commits into from
Dec 6, 2024
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
5 changes: 3 additions & 2 deletions src/node/SetupServerCommonApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,6 @@ export class SetupServerCommonApi
})

this.resolvedOptions = {} as RequiredDeep<SharedOptions>

this.init()
}

/**
Expand Down Expand Up @@ -141,7 +139,10 @@ export class SetupServerCommonApi
) as RequiredDeep<SharedOptions>

// Apply the interceptor when starting the server.
// Attach the event listeners to the interceptor here
// so they get re-attached whenever `.listen()` is called.
this.interceptor.apply()
this.init()
this.subscriptions.push(() => this.interceptor.dispose())

// Apply the WebSocket interception.
Expand Down
61 changes: 61 additions & 0 deletions test/node/regressions/2370-listen-after-close.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/**
* @see https://github.com/mswjs/msw/issues/2370
*/
// @vitest-environment node
import { http, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'
import { HttpServer } from '@open-draft/test-server/http'

const server = setupServer()

const httpServer = new HttpServer((app) => {
app.get('/resource', (_req, res) => {
res.send('original')
})
})

beforeAll(async () => {
server.listen()
await httpServer.listen()
})

afterEach(() => {
server.resetHandlers()
})

afterAll(async () => {
server.close()
await httpServer.close()
})

it('intercepts a request once `server.listen()` is called after `server.close()`', async () => {
const requestUrl = httpServer.http.url('/resource')

server.use(
http.get(requestUrl, () => {
return HttpResponse.text('mocked')
}),
)

// Must respond with a mocked response while MSW is active.
{
const response = await fetch(requestUrl)
await expect(response.text()).resolves.toBe('mocked')
}

server.close()

// Must respond with the original response once MSW is closed.
{
const response = await fetch(requestUrl)
await expect(response.text()).resolves.toBe('original')
}

server.listen()

// Must respond with the mocked response once MSW is active again.
{
const response = await fetch(requestUrl)
await expect(response.text()).resolves.toBe('mocked')
}
})
Loading