eugef / node-mocks-http

Mock 'http' objects for testing Express,js, Next.js and Koa routing functions
Other
755 stars 134 forks source link

What happens if you have a database call in your handler? #287

Closed Meags27 closed 9 months ago

Meags27 commented 9 months ago

I'm new to testing API routes and I'm using Next.js App router.

I understand you create a mock request and response object and pass that into your handler, but what if your handler makes a database call to your database or a call to a third party API, does node-mocks-http prevent that call somehow to avoid the network call inside your handler?

I'm struggling to understand what this library is for?

  1. Is it a unit test? Are we mocking the request and response itself? If so, what's the point, aren't you faking the whole flow and not testing the actual code?
  2. Is it an integration test? Are you creating a local database to test against and faking the request?

Thank you!

eugef commented 9 months ago

Hi @Meags27

does node-mocks-http prevent that call somehow to avoid the network call inside your handler

No, you should use other libraries to mock API calls, for example nock or mswjs. If you make db calls, just google for mock library-name-used-to-make-db-calls to find a proper mock.

Is it a unit test? Is it an integration test?

This library can be used for both type of testing. If you mock all external dependencies of the handler - then it is a unit test; if not - then it is more an integration test.

Meags27 commented 9 months ago

Hi @Meags27

does node-mocks-http prevent that call somehow to avoid the network call inside your handler

No, you should use other libraries to mock API calls, for example nock or mswjs. If you make db calls, just google for mock library-name-used-to-make-db-calls to find a proper mock.

Is it a unit test? Is it an integration test?

This library can be used for both type of testing. If you mock all external dependencies of the handler - then it is a unit test; if not - then it is more an integration test.

Ah thank you that makes sense, I ended up using aws-sdk-client-mock to mock the database/aws api calls.

And that makes sense, integration testing would be using this with a local database, unit testing is mocking the api calls.