Javascript 如何(我可以?)根据请求数据在截获内加载Cypress fixture?
我有一组由后端生成的装置,它们是根据请求体的散列来命名的。 我试图找到一种基于发送的请求动态加载装置的方法,如下所示:Javascript 如何(我可以?)根据请求数据在截获内加载Cypress fixture?,javascript,cypress,fixtures,Javascript,Cypress,Fixtures,我有一组由后端生成的装置,它们是根据请求体的散列来命名的。 我试图找到一种基于发送的请求动态加载装置的方法,如下所示: cy.intercept('POST', '**/login', (req) => { const hash = md5(req.body); cy.fixture(`${hash}.json`).then(data => { req.reply(res => { res.statusCode = dat
cy.intercept('POST', '**/login', (req) => {
const hash = md5(req.body);
cy.fixture(`${hash}.json`).then(data => {
req.reply(res => {
res.statusCode = data.statusCode;
res.body = data.body;
})
})
}).as('response');
cy.visit("/login");
cy.get('input[name="email"]').type('test@email.com');
cy.get('input[name="password"]').type('wrongpassword');
cy.contains('button', 'Login').click();
cy.wait('@response');
cy.contains('Invalid credentials.');
但每次尝试在截距内加载夹具时,都会出现以下错误:
The following error originated from your test code, not from Cypress.
> A request callback passed to cy.intercept() threw an error while intercepting a request:
Cypress detected that you returned a promise from a command while also invoking one or more cy commands in that promise.
The command that returned the promise was:
> cy.wait()
The cy command you invoked inside the promise was:
> cy.fixture()
有没有办法,我可以根据请求中的内容动态加载装置?您可以先读取装置
cy.fixture('login_incorrect.json')。然后(data=>{//可能不需要它,但万一。。。
cy.intercept('POST'、'**/login'、(req)=>{
const body=JSON.parse(req.body);
如果(body.password==='errowpassword'){
请求回复(res=>{
res.statusCode=data.statusCode;//数据=上面的闭包
res.body=data.body;
})
}否则{
//根据某物等装载不同的夹具。
}
}).as(“响应”);
})
组合夹具
{
"put-first-hash-here": {
statusCode: ...,
body: ...
},
"put-second-hash-here": {
statusCode: ...,
body: ...
},
}
测试
cy.fixture('combined.json')。然后(数据=>{
cy.intercept('POST'、'**/login'、(req)=>{
const body=JSON.parse(req.body);
const hash=md5(请求主体);
如果(body.password==='errowpassword'){
请求回复(res=>{
res.statusCode=数据[hash].statusCode;
res.body=data[hash].body;
})
}
}).as(“响应”);
})
嘿,谢谢你的回答。事实上,我意识到我的问题并不精确,所以我更新了它。ps:我真的需要根据请求本身找到正确的fixture。实用的答案是,要么预加载所有fixture-可以有多少个:)-或者将所有fixture合并到一个json文件中,其中包含一个对象,哈希作为键。是的,我想我会预先加载所有fixture。谢谢