No match error when testing an Express.js controller doing multiple calls to a same backend
Posted on
Trouble
Getting Nock: No match for request ...
with error code ERR_NOCK_NO_MATCH
Context
I had a controller requesting the same backend service but onto 2 different endpoints. My intent was to mock these calls using the great "HTTP server mocking and expectations library for Node.js" Nock. This intent take the form of the below code:
const scope = nock('http://backend')
.get('/user/details')
.reply(200, {
userId: 123,
email: '123@example.com'
})
.post('/api')
.reply(200, {
data: {
// data to be returned
}
});
When my controller was reaching the /user/details
endpoint it was being
matched and resolved, but when it was reaching the /api
on it was getting
Nock: No match for request /api
exception.
I knew that interceptors, as stated in the Nock documentation, are removed as
they are used. Though, in my opinion I did not considered the /api
as yet used
because of the misleading message telling me it could not be matched.
Solution
The solution was to append the call to the .persist()
method between
nock('http://backend')
and get('/user/details')
as shown in code below:
const scope = nock('http://backend')
.persist()
.get('/user/details')
.reply(200, {
userId: 123,
email: '123@example.com'
})
.post('/api')
.reply(200, {
data: {
// data to be returned
}
});
I would have found the .persist()
call to be more intuitive if scoped at
endpoint level rather than at hostname level though. Well at least now my test
passes 🎉.