gpt4 book ai didi

node.js - Cypress 在浏览器外部执行 API 调用

转载 作者:太空宇宙 更新时间:2023-11-03 22:05:23 25 4
gpt4 key购买 nike

我使用 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');
});

插件/index.js

const FOY = require('../resetScripts/talentMine/FOY');

module.exports = (on, config) => {
on('task', {
'TMDeleteFOY': (emailaddress) => {
return FOY.TMUpdateFOY(emailaddress);
}
})
};

最佳答案

您需要从任务代码中返回一些内容,以便 Cypress 知道要等待什么,并在运行其他代码之前知道您的任务已完成。

查看 cy.task() documentation :

In the task plugin event, the command will fail if undefined is returned. This helps catch typos or cases where the task event is not handled.

要解决此问题,您只需修改任务代码即可返回 promise 。目前,您没有返回任何内容。

在您的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...

关于node.js - Cypress 在浏览器外部执行 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55520300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com