I created a simple application using create-react-app. I am now trying to write some automated test cases using @testing-library and Mock Service Worker. For reasons unknown to me when I POST a request using Window.fetch (or just fetch) the body of the response is not returned.
I am using the following dependencies:
"@testing-library/react": "^11.2.5",
"@testing-library/user-event": "^12.7.1",
"msw": "^0.28.0",
"react": "^17.0.1"
I have the following test:
import { rest } from 'msw';
import { setupServer } from 'msw/node';
const MOCKED_URL = 'http://mock.example.net:8080/foo'
let server = setupServer(
rest.post(MOCKED_URL, (req, res, ctx) => {
return res(
ctx.status(200),
ctx.json(req.body),
)
}),
)
beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close())
test('send POST request with body via superagent', async () => {
let response = await window.fetch(MOCKED_URL, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
headers: { 'Content-Type': 'application/json' },
body: { bar: 6, baz: '34' }
});
console.log(response);
expect(response.body).toMatchObject({
bar: 6,
baz: '34',
})
});
The output from the console.log(response)
is
type: 'default',
status: 200,
ok: true,
statusText: 'OK',
headers: Headers {
map: { 'x-powered-by': 'msw', 'content-type': 'application/json' }
},
url: '',
bodyUsed: false,
_bodyInit: Blob {},
_bodyBlob: Blob {}
}
Can anyone explain why the body is not returned and how I can get this test to work?
Aucun commentaire:
Enregistrer un commentaire