I'm struggling to find a way to intercept the getServerSideProps when using cypress component testing.
After extensive research, I found some useful resources:
Link 3
If you're interested, you can also check out this example repository: Example Repo
The objective is to achieve the following:
cypress/plugins/index.ts
const http = require('http');
const next = require('next');
const nock = require('nock');
// Start the Next.js server when Cypress starts
module.exports = async (on, config) => {
const app = next({ dev: true });
const handleNextRequests = app.getRequestHandler();
await app.prepare();
on('dev-server:start', async () => {
const customServer = new http.Server(async (req, res) => {
return handleNextRequests(req, res);
});
await new Promise<void>((resolve, reject) => {
customServer.listen(3000, err => {
if (err) {
return reject(err);
}
console.log('> Ready on http://localhost:3000');
resolve();
});
});
return customServer;
});
on('task', {
clearNock() {
nock.restore();
nock.clearAll();
return null;
},
async nock({ hostname, method, path, statusCode, body }) {
nock.activate();
console.log({ hostname, method, path, statusCode, body });
method = method.toLowerCase();
nock(hostname)[method][path].reply(statusCode, body);
return null;
},
});
return config;
};
components/AddProperty/index.spec.ct.tsx
import { mount } from '@cypress/react';
import Component from './index';
beforeEach(() => {
cy.task('clearNock');
});
it.only('queries the api', () => {
cy.fixture('properties').then((properties: Property[]) => {
cy.task('nock', {
path: '/api/address?q=*',
method: 'GET',
statusCode: 200,
body: {
json: function () {
return [{ id: '42', adressebetegnelse: 'Beverly Hills' } as Partial<Property>];
},
},
});
cy.intercept('GET', '/api/address?q=*', properties).as('getProperties');
mount(<Component />);
cy.contains('Beverly Hills');
cy.get('input').type('Some address{enter}');
cy.wait('@getProperties').its('response.statusCode').should('eq', 200);
properties.forEach(property => {
cy.contains(property.adressebetegnelse);
});
});
});
However, the tests won't run properly. Any insights or tips would be appreciated!