(Cypress) cy.intercept Does Not Support Server Side Rendering in Next.js
Introduction
Below is an example. All the tests pass.
Folder Structure
cypress
|-e2e
|-test.js
pages
|-csr.jsx
|-ssr.jsx
cypress.config.js
Cypress Configuration
|cypress.config.js|
const { defineConfig } = require('cypress');
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {},
specPattern: 'cypress/e2e/**/*.{js,jsx,ts,tsx}',
baseUrl: 'http://localhost:3000/',
supportFile: false,
},
});
Codes
|csr.jsx|
import { useEffect, useState } from 'react';
export default function () {
const [title1, setTitle1] = useState('');
useEffect(() => {
(async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = await response.json();
setTitle1(data[0].title);
})();
}, []);
return <p>{title1}</p>;
}
|ssr.jsx|
export default function ({ data }) {
return <p>{data[0].title}</p>;
}
export async function getServerSideProps() {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = await response.json();
return {
props: {
data,
},
};
}
|test.js|
/// <reference types="cypress" />
const mockTitle = 'mock';
const originalTitle = 'sunt';
describe('ssr testing', () => {
before(() => {
cy.intercept(
{
method: 'GET',
url: '**/jsonplaceholder.typicode.com/**',
},
{
statusCode: 200,
body: [
{
title: mockTitle,
},
],
}
);
});
it('csr', () => {
cy.visit('/csr');
cy.contains(mockTitle).should('exist');
});
it('ssr', () => {
cy.visit('/ssr');
cy.contains(originalTitle).should('exist');
});
});