我使用axios创建了函数,这些函数将在每次测试运行之前设置测试数据。它们位于FOY.js文件中
const axios = require('axios');
//Get the token needed for Bearer Authorization
async function getJWT() {
const bearerToken = await axios.post('https://www.example.com', {username: 'user', password: 'test1234'});
return bearerToken.data.access_token
}
//Get the UserId from the email address.
async function getUserId(emailAddress) {
var bearerToken = await getJWT();
const userId = await axios.get('https://example.com/users/search?contains='+emailAddress+'', {'headers':{Authorization: 'Bearer '+bearerToken+''}});
console.log(userId.data.users[0].id);
return userId.data.users[0].id
}
//Delete a record for a user
async function TMDeleteFOY (emailAddress) {
var bearerToken = await getJWT();
var userId = await getUserId(emailAddress);
const response = await axios.delete('https://example2.com/'+userId+'/record', {'headers':{Authorization: 'Bearer '+bearerToken+''}});
return response.status
}
module.exports.TMDeleteFOY = TMDeleteFOY;
module.exports.TMUpdateFOY = TMUpdateFOY;
使用cy.task()
beforeEach(function() {
cy.task('TMDeleteFOY', 'example@mail.com');
});
plugins / index.js
const FOY = require('../resetScripts/talentMine/FOY');
module.exports = (on, config) => {
on('task', {
'TMDeleteFOY': (emailaddress) => {
return FOY.TMUpdateFOY(emailaddress);
}
})
};
答案 0 :(得分:1)
您需要从任务代码中返回一些内容,以便赛普拉斯知道要等待什么,并知道在执行其他代码之前您的任务已完成。
在
task
插件事件中,如果返回undefined,该命令将失败。这有助于捕捉错别字或未处理任务事件的情况。
要解决此问题,您只需修改您的任务代码,以便返回承诺。现在,您什么都没退。
在您的plugins/index.js
中:
const FOY = require('../resetScripts/talentMine/FOY');
module.exports = (on, config) => {
on('task', {
'TMDeleteFOY': (emailaddress) => {
// CHANGED: return a promise so Cypress can wait for it
return FOY.TMDeleteFOY(emailaddress);
}
})
}
在您的FOY.js
文件中(为简洁起见,不相关的部分已排除):
// start of your FOY.js...
//Delete a record for a user
async function TMDeleteFOY (emailAddress) {
var bearerToken = await getJWT();
var userId = await getUserId(emailAddress);
// CHANGED: return this promise chain so Cypress can wait for it
return await axios.delete('https://example2.com/'+userId+'/record', {'headers':{Authorization: 'Bearer '+bearerToken+''}});
}
// end of your FOY.js...