Skip to content

Instantly share code, notes, and snippets.

@rabeehebrahim
Created June 6, 2023 17:00
Show Gist options
  • Save rabeehebrahim/6f0d738868604e5202dc7177b09e3512 to your computer and use it in GitHub Desktop.
Save rabeehebrahim/6f0d738868604e5202dc7177b09e3512 to your computer and use it in GitHub Desktop.
Replacing jwt token verification middleware when testing end points in jest.
// before importing app and supertest
// you should write jest.mock function
// with the first argument is the path of your
// actual middleware and second argument write a
// fake middle function.
jest.mock('../middleware/verifyToken', () => {
return jest.fn((req, res, next) => {
next()
})
})
import mongoose from 'mongoose'
import supertest from 'supertest'
import app from '../app'
const requestWithSupertest = supertest(app)
describe('User Endpoints', () => {
const mockUserId = '647f528fe307c6317c3c7629'
it('GET /users/id should return a user', async () => {
const response = await requestWithSupertest.get(`/users/${mockUserId}`)
expect(response.status).toEqual(200)
expect(response.type).toEqual(expect.stringContaining('json'))
expect(response.body).toHaveProperty('status', 'success')
expect(response.body).toHaveProperty('message', 'Successfully fetched the user details.')
const { data } = response.body // Get the data from the response body
expect(data.user).toHaveProperty('_id') // check weather it contain user object with '_id' property
})
afterAll(async () => {
await mongoose.disconnect()
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment