Skip to content

Instantly share code, notes, and snippets.

@aptiko
Created May 18, 2021 10:18
Show Gist options
  • Save aptiko/90b770eeeeb01b5dec6a3b695e80972e to your computer and use it in GitHub Desktop.
Save aptiko/90b770eeeeb01b5dec6a3b695e80972e to your computer and use it in GitHub Desktop.
Setting up MSW with Jest
import { rest } from 'msw'
import { setupServer } from 'msw/node'
describe('LoginForm', () => {
let server
beforeAll(() => {
server = setupServer(
rest.post('/auth/login/', (request, response, context) => {
const username = request.body.username
const password = request.body.password
if (username === 'alice' && password === 'topsecret')
return response(context.json({ key: 'topsecretkey' }))
else if (username === 'alice' && password === 'wrongpassword')
return response(
context.status(400),
context.json({ non_field_errors: 'Wrong password' })
)
else throw new Error('Something went wrong')
})
)
server.listen()
})
afterAll(() => {
server.close()
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment