Skip to content

Commit

Permalink
fix(setupServer): reapply interception after calling `server.listen()…
Browse files Browse the repository at this point in the history
…` after `server.close()` (#2383)
  • Loading branch information
kettanaito authored Dec 6, 2024
1 parent e8d748e commit 00da9ca
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 2 deletions.
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')
}
})

0 comments on commit 00da9ca

Please sign in to comment.