Search code examples
node.jsnext.jsmockingcypressnock

Nock not mocking requests on Nextjs and Cypress


In some pages, we use getInitialProps that makes a request on the backend side to call an external endpoint. On the CI/CD machine we can´t call this other endpoint so we want to mock that endpoint. Im trying to centralize the mocked server so I dont need to initialize it on each test that im making and for the future tests.

Under cypress.config.ts I saw that I can add a before:run event under e2e property that I believe will create the endpoint that will intercept all the requests for that endpoint on the tests:

on('before:run', async (details) =>
  await nock(/.*?(localhost:4000|{_another_endpoints_regex_here}).*?/)
    .get('/api/')
    .reply(200, {data:"data"})
})

I added an regex since the requested url changes between environments, also I have enabled the experimentalInteractiveRunEvents flag, I added an console log there and it is showing on console. Also I moved that code inside my page and its working correctly so I believe the issue is not that code.

I wonder why nextjs request its not being mocked? Its an issue related to cypress or nock?

The error that I get is:

data: {
      message: 'request to http://localhost:4000/api/ failed, reason: connect ECONNREFUSED 127.0.0.1:4000',
      type: 'system',
      errno: 'ECONNREFUSED',
      code: 'ECONNREFUSED'
    }

*If its needed, I can use another framework to mock the requests


Update: I have created a new isolated nextjs endpoint and a cypress test to test. Also I tried using MSW and moving the code inside support/e2e.ts in beforeEach hook without success


Update 2: So after digging in whole the proyect, I believe the issue is how im executing the tests. Im using start-server-and-test package to run the proyect and then execute cypress. I believe this makes two instances of nodejs making cypress and nextjs be on different scope so nock can't be reached by nextjs. How can I execute cypress and nextjs together without using that package?


Solution

  • As mentioned on my OP, looks like I can´t mock backend requests on cypress using nock, msw, or whatever since I believe start-server-and-test create different instances of nodejs, and I believe those mocking tools what does at the end is kind of modify fetch/http methods, but since they run on different instances they dont modify those methods of the instance that is running nextjs.

    So afterall, I solved my issue by creating a server that runs on port 4000 with json-server to imitate the server and on nextjs side on .env.development I changed the backend url so it points to the localhost:4000 endpoint and in cypress.config.ts I create the server inside the e2e property inside setupNodeEvents using before:run

    e2e: {
        setupNodeEvents(on, config) {
          on('before:run', () => {
            //code to create a json-server()
          })
        },
    }