Does advice to avoid request assertions apply to server-side tests? #1682
-
I just started using I'm getting hung up on one thing, though. Tests from before we switched to
I'm simplifying things a bit, but you get the idea. Our service acts as a sort of "translation layer" between other services and we need to test that the translation is correct. If I don't do that by making expectations against the POST body, what's the "right" way to do it instead? I did find #866 and the docs that are linked there, with an example of how to check request details using lifecycle events, but before I start down that path, I wanted to make sure I'm not setting myself up for failure later. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hi, @thw0rted. As a good place to start, I recommend reading through Request assertions. MSW generally discourages those since they often lead developers astray from testing what actually matters (the state/UI derived from the correct requests/responses). If you are testing a service that's an intermediate layer and doesn't have any direct state to assert, then I recommend looking into Life-cycle events to track and assert the response, or implementing the following pattern: import { DeferredPromise } from '@open-draft/deferred-promise'
import { server } from './your-msw-setup'
it('reformats the name parameter', async () => {
const responseBodyPromise = new DeferredPromise()
// Await the mocked response for the resource requested in "createForm".
server.events.on('response:mocked', (response, request) => {
if (request.url.pathname === '/resource/you/requested') {
responseBodyPromise.resolve(JSON.parse(response.body))
}
})
await createForm({ name: 'ABC 123' })
// Assert the awaited mocked response.
const actualResponseBody = await responseBodyPromise
expect(actualResponseBody).toEqual({ name: 'abc_123' })
})
|
Beta Was this translation helpful? Give feedback.
Hi, @thw0rted.
As a good place to start, I recommend reading through Request assertions. MSW generally discourages those since they often lead developers astray from testing what actually matters (the state/UI derived from the correct requests/responses).
If you are testing a service that's an intermediate layer and doesn't have any direct state to assert, then I recommend looking into Life-cycle events to track and assert the response, or implementing the following pattern: