I have a piece of middleware that performs authentication with a third-party service via request. I do this request with superagent. Obviously I want to mock this in my tests since it slows them down quite a lot and also is dependant on the third-parties server.
When using nock, it doesn't seem to find the request at all. I even tried using the recorder and it only picks up the actual requests of my local endpoints. (Although it uses an unfamiliar IP and port?).
The request inside my middleware;
export default async (req, res, next) => {
const user = await superagent
.get(`https://example.com/session/`)
.query({ session })
.set('Api-Key', '1234');
}
My Nock Instance;
nock('https://example.com/session/')
.persist()
.get('/session/')
.reply(200, {
success: true,
username: 'testuser',
})
.log(console.log);
You have 2 issues here.
First off, you define twice /session/
:
nock('https://example.com/session/')
.get('/session/')
Choose:
nock('https://example.com').get('/session/')
nock('https://example.com/session/').get('/')
Second issue, you're adding a query string to your call (.query({ session })
), but you don't tell that to Nock using .query(true)
.
In the end, you should have something like:
nock('https://example.com/session/')
.persist()
.get('/') // rewrote here
.query(true) // added here
.reply(200, {
success: true,
username: 'testuser',
})
.log(console.log);