基于 Cypress docs,我想在首次加载夹具后修改响应上的字段并保持其他所有内容不变。我知道我可以轻松地使用 2 个灯具来完成此操作,但我不想为了简单的现场更改而重复它。我尝试了以下代码的变体,但没有成功。有什么想法吗?
it('Should have the correct values in monthly', () => {
cy.intercept('POST', `**/full`, (req) => {
req.continue(res => {
res.body.data.monthly = 5000;
res.send(res);
})
});
cy.fixture('calculator/monthlyRepayment.json').as('fixtures:monthlyRepayment');
cy.route('POST', `**/full`, '@fixtures:monthlyRepayment').as(`request:fullData`);
cy.get('[data-test="calculator:monthlyRepayment"]').should('contain', '$5000.00');
})
我留下了评论,但这也能解决你的问题。您需要在使用之前修改您的灯具数据:
it('Should have the correct values in monthly', () => {
cy.fixture('calculator/monthlyRepayment.json').then((json) => {
json.monthly = 5000;
cy.intercept('POST', '**/full', json);
// cy.visit called somewhere here
cy.get('[data-test="calculator:monthlyRepayment"]').should('contain', '$5000.00');
});
})
为此,我定义了一个可重用的
interceptWithFixtureHook
命令:
export type FixtureHook<T> = (data: T) => T | void;
export function interceptWithFixtureHookFn<T>(
url: RouteMatcher,
fixturePath: string,
fixtureHook: FixtureHook<T>
) {
return cy.fixture<T>(fixturePath).then((fixtureData) => {
const getData = (): T => {
const data = structuredClone(fixtureData);
const modifiedData = fixtureHook(data); // may mutate `data`
return modifiedData ?? data;
};
return cy.intercept(url, (req) => {
req.reply({ body: getData() });
});
});
}
Cypress.Commands.add('interceptWithFixtureHook', interceptWithFixtureHookFn);
然后您可以在每次测试中动态修改您的夹具基础数据:
type MyData = { monthly: number };
let monthly: number;
beforeEach(() => {
cy.interceptWithFixtureHook<MyData>(
{ method: 'POST', url: `**/full` },
'calculator/monthlyRepayment.json',
(data) => {
data.monthly = monthly;
}
);
});
it('should do something', () => {
monthly = 42;
cy.get('[data-test="calculator:monthlyRepayment"]').should('contain', '$42.00');
});
it('should do something else', () => {
monthly = 5000;
cy.get('[data-test="calculator:monthlyRepayment"]').should('contain', '$5000.00');
});