samedi 27 mars 2021

What is a good way to to mock and spy on an API dependency in Node testing?

I have a question about how best to do front-end/integration testing without having to mock an entire API. I've not found any great solutions and I'm starting to wonder if I'm thinking about this the wrong way.

My situation

I have a web client that I want to test which relies heavily on a REST API that is part of our larger system. For the most part, testing against an instance of the real API service seems like the right thing to do in our integration testing scenario, but in some cases (e.g. provoking errors, empty lists et c) it would be easier to mock portions of the API than to go in and change the actual state of the API service.

In other cases, I don't need to mock the API, but I do need to confirm that requests were made as expected, essentially a spy, but on an API.

My idea for a solution

I imagined the best way to solve this would be an HTTP proxy controlled by the test suite, sitting between the system-under-test and the API service. The test suite would then:

  • Configure the system-under-test to use the API proxy
  • For each test
    • Set up mocks only on relevant endpoints (the rest are proxied to the API service)
    • Exercise the system-under-test
    • Make assertions by reading spies from the proxy
    • Tear down/reset the mocks and spies afterwards

I have multiple use cases for this, one being Cypress end-to-end testing inside a browser, where monkeypatching or dependency injection is not possible, because significant portions of the system under test is not executed directly by the test-suite.

I found MockServer which seems to solve what I'm looking to achieve, but in a massive Java program that adds a lot of requirements (e.g. Java, which translates to CI costs) to an otherwise node-based environment.

My question(s)

Is what I'm considering a good approach to this type of situation? What is a good way (e.g. existing software) to solve this within the Node eco-system?

Aucun commentaire:

Enregistrer un commentaire