我有一个非常基本的 Cypress 组件测试,可以拦截 API 请求。请求响应包括在被测试的组件中呈现的图像的 URL。该响应被保存为名为 selectedLogo 的状态对象,并且所显示图像的 src 取自 selectedLogo.url 的值。我已将图像的副本保存到装置文件夹中 - 如何让 Cypress 显示它来代替原始图像?
这是测试:
import React from 'react';
import Logo from '../../src/logo/logo';
const allApiInterceptors = () => {
cy.intercept('/logos/123456', {
id: 5295911,
url: '../fixtures/Banner.jpg' // this doesn't work
});
};
describe('Logo', () => {
beforeEach(() => {
allApiInterceptors();
});
it('mounts', () => {
cy.mount(<Logo />);
});
});
在被测试的React组件中,创建了一个状态对象:
const [selectedLogo, setSelectedLogo] = useState(null);
对 API 请求的响应保存到状态对象中:
setSelectedLogo(response);
组件中的图像从状态对象中获取它的 src:
{selectedLogo && (
<img src={selectedLogo.url} />
)}
要在 Cypress 测试过程中显示 Fixtures 文件夹中的图像来代替原始图像,不能在 cy.intercept 拦截的响应中直接使用相对路径“../fixtures/Banner.jpg”。您应该使用 cy.fixture() 加载夹具,然后将其作为响应返回。像这样的东西,
import React from 'react';
import Logo from '../../src/logo/logo';
const allApiInterceptors = () => {
cy.intercept('/logos/123456', (req) => {
req.reply((res) => {
res.send({
id: 5295911,
url: 'Banner.jpg' // Adjust this according to your actual folder structure
});
});
}).as('logoRequest');
};
describe('Logo', () => {
beforeEach(() => {
allApiInterceptors();
});
it('mounts', () => {
cy.fixture('Banner.jpg').then((image) => {
cy.mount(<Logo />, {
state: { selectedLogo: { url: image } }
});
});
cy.wait('@logoRequest'); // ensure the intercept is called
});
});