无法弄清楚使用 cypress 组件测试时如何拦截 getServerSideProps。
做了很多研究和最好的引导链接:
https://github.com/cypress-io/cypress/discussions/9328
https://www.youtube.com/watch?v=33Hq41O0bvU
https://glebbahmutov.com/blog/mock-network-from-server/
https://www.youtube.com/watch?v=xdVRVhUUgCI&feature=youtu.be
有这个例子回购:https ://github.com/norfeldt/proper/tree/ssr-stubing
我想做的是:
赛普拉斯/插件/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;
};
组件/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);
});
});
});
但它甚至不会运行测试