gpt4 book ai didi

javascript - 如何将动态 `groupID`从一个js文件传递到另一个js文件

转载 作者:行者123 更新时间:2023-12-03 02:30:06 25 4
gpt4 key购买 nike

我已附上我的代码供引用,因为我想将动态groupIDteamgroupapi.js传递到teamCategoryApi.js

当我尝试从 ApiCategory.js 文件手动传递 groupID 时,代码工作正常。

文件名teamgroupapi.js

import { getGeneratedApi } from '@test/bender-executor-simple-api-generator';
import ApiGroup from '../_support/ApiGroup.js';


const request = require('supertest');
const fs = require('fs');
const assert = require('assert')
const chakram = require ('chakram');
const expect = chakram.expect;

const swaggerPath = process.env.BENDER_SWAGGER_PATH || 'https://api-s10938402.cc-staging.test.com/documentation/api.yaml';
const token = process.env.BENDER_LOGIN_TOKEN || 'JTFihw2GJbJ87duTihoGW3vBi8MErxTbBJsD4dw6k5MsPmfI0J8lsf9-mRFXufFYYMzEVcEdK8kXEi3EVkojHQ';
console.log(`login token is ${token}`);
const apiUrl = 'https://' + (process.env.CC_URL_API || 'api-s10938402.cc-staging.test.com');

const readJsonTestFile = (testfilename) => {
return JSON.parse(fs.readFileSync(testfilename, 'utf8'));
};


describe('Create Group all api generated', () => {

let api;
let groupID;
let apiGroup;
const groupName = "Test_" + new Date().getTime();
const groupName_rename = "Rename_" + new Date().getTime();

//const groupJson = { "name": groupName };
//const grouprenameJson = { "name": groupName_rename };

beforeAll(async () => {
api = await getGeneratedApi(apiUrl, token, swaggerPath);
console.log(api);
apiGroup = new ApiGroup();
});

beforeEach(async () => {
// TODO setup.cleanupDb();
// await setup.gateway();
});
//Create Group API
test('Create Group', async() => {
try
{
jest.setTimeout(10000);
console.log("Create Group");
//const payload = readJsonTestFile('e2e/example.json');
const groupJson = apiGroup.generateCreateGroupJsonObject(groupName);
const createGroup = await api.postTeamGroups(groupJson);
//const listofGroups = JSON.parse(JSON.stringify(createGroup));
//expect(result.response.statusCode).toBe(201);
expect(createGroup).to.have.status(201);
console.log("Create group successfully executed");
} catch(e){
console.log("Failed to create group");
throw e;
}
});
//Get Group API
test('Get Group API', async() => {
try
{
jest.setTimeout(10000);
console.log("Get Created Group");
let foundIndex = -1;
console.log("Running get group and attempting to get ::: " + groupName);
//Check if previously created Group exists using the GET Group API
//Check the response payload and loop through the response to find the workspace that was created earlier
const getGroup = await api.getTeamGroups(false,false);
//const listofGroups = JSON.parse(JSON.stringify(getGroup));
//console.log("list of groups" + getGroup.body.length);
expect(getGroup).to.have.status(200);
for(var i = 0; i < getGroup.body.length;i++){
if((getGroup.body[i].name == groupName) && (getGroup.body[i].id != '') ) {
foundIndex = i;
break;
}
}
groupID = getGroup.body[i].id;
console.log("Group ID ---->>>>" + getGroup.body[i].id);
console.log("Group Name ---->>>>" + getGroup.body[i].name);
expect(foundIndex).to.be.above(-1);
console.log("Get group successfully executed");
} catch(e){
console.log("Failed to get group");
throw e;
}
});
// Rename Group API
test.skip('Rename Group API with Group ID', async()=> {
try
{
jest.setTimeout(10000);
console.log("Rename already created group");
const groupJson = apiGroup.generateCreateGroupJsonObject(groupName_rename);
const apigroup = await api.postTeamGroupsWithGroupID(groupID,groupJson);
expect(apigroup).to.have.status(200);
console.log("Rename group successfully executed");
} catch(e){
console.log("Failed to rename group");
throw e;
}
});
//Delete Group API
test.skip('Delete Group API', async()=> {
try
{
jest.setTimeout(10000);
console.log("Delete Created Group");
console.log("Running delete group and attemptin to delete ::: " + groupID);

const apigroup = await api.deleteTeamGroupsWithGroupID(groupID);

expect(apigroup).to.have.status(200);
console.log("Delete group successfully executed");
} catch(e){
console.log("Failed to delete group");
throw e;
}
});
});

teamgroupapi.js 的单独 Json 函数 文件名 ApiGroup.js

class ApiGroup {

constructor()
{
//super();
}

generateCreateGroupJsonObject(groupName) {

return {
"name": groupName
}
}
}

module.exports = ApiGroup;

文件名teamCategoryApi.js

import { getGeneratedApi } from '@test/bender-executor-simple-api-generator';
import ApiCategory from '../_support/ApiCategory.js';
import teamgroupapi from './teamgroupapi.js';

const request = require('supertest');
const fs = require('fs');
const assert = require('assert')
const chakram = require ('chakram');
const expect = chakram.expect;

const swaggerPath = process.env.BENDER_SWAGGER_PATH || 'https://api-s10938402.cc-staging.test.com/documentation/api.yaml';
const token = process.env.BENDER_LOGIN_TOKEN || 'JTFihw2GJbJ87duTihoGW3vBi8MErxTbBJsD4dw6k5MsPmfI0J8lsf9-mRFXufFYYMzEVcEdK8kXEi3EVkojHQ';
console.log(`login token is ${token}`);
const apiUrl = 'https://' + (process.env.CC_URL_API || 'api-s10938402.cc-staging.test.com');

const readJsonTestFile = (testfilename) => {
return JSON.parse(fs.readFileSync(testfilename, 'utf8'));
};

describe('Create category all api generated', () => {

let api;
let categoryID;
let apiCategory;
let groupID;
//let teamGroup;
const categoryName = "Test_" + new Date().getTime();
const categoryName_rename = "Rename_" + new Date().getTime();
//const categoryrenameJson = { "name": categoryName_rename };

beforeAll(async () => {
api = await getGeneratedApi(apiUrl, token, swaggerPath);
console.log(api);
apiCategory = new ApiCategory();
//teamGroup = new teamgroupapi();
//console.log(api);
});

beforeEach(async () => {
// TODO setup.cleanupDb();
// await setup.gateway();
});

//Create Category API
test('Create Category', async () => {
jest.setTimeout(20000);
try {
console.log("Create Category");
/*const groupID = teamGroupApi.groupID;
let api = teamGroupApi.api;*/
/*groupID = teamgroupapi.groupID;
console.log(groupID);*/

const categoryJson = apiCategory.generateCreateCategoryJsonObject(categoryName,groupID);
//const categoryJson = { "name": categoryName, "groupId": groupID, "parent": 0 };
const createCategory = await api.postTeamCategories(categoryJson);
//const listofCategories = JSON.parse(JSON.stringify(createCategory));
//expect(result.response.statusCode).toBe(201);
expect(createCategory).to.have.status(201);
console.log("Create category successfully executed");
}
catch (e)
{
console.log("Failed to create category");
throw e;
}
});

//Get Category API
test.skip('Get Category API', async() => {
jest.setTimeout(20000);
try {
console.log("Get Created Category");
let foundIndex = -1;
//const categoryName = "Test_" + new Date().getTime();
console.log("Running get category and attempting to get ::: " + categoryName);
//Check if previously created Group exists using the GET Group API
//Check the response payload and loop through the response to find the workspace that was created earlier
//let api = teamGroupApi.api;

const getCategory = await api.getTeamCategories();
//const listofCategories = JSON.parse(JSON.stringify(apicategory));
//console.log("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
//console.log("list of category" + apicategory.body.length);
expect(getCategory).to.have.status(200);
for(var i = 0; i < getCategory.body.length;i++){
if((getCategory.body[i].name == categoryName) && (getCategory.body[i].id != '') ) {
foundIndex = i;
break;
}
}
categoryID = getCategory.body[i].id;
console.log("Category Name ---->>>>" + getCategory.body[i].id);
console.log("Category Name ---->>>>" + getCategory.body[i].name);
expect(foundIndex).to.be.above(-1);
console.log("Get Category successfully executed");
}
catch (e)
{
console.log("Failed to get category");
throw e;
}
});

//Rename Category API
test.skip('Rename Category API with categoryID', async()=> {
jest.setTimeout(20000);
try {
console.log("Rename already created category");

const renameCategoryJson = apiCategory.renameCreateCategoryJsonObject(categoryName_rename);

//const groupJson = apiGroup.generateCreateGroupJsonObject(groupName_rename);
const apicategory = await api.postTeamCategoriesWithCategoryID(categoryID,renameCategoryJson);

//const apicategory = await api.postTeamCategoriesWithCategoryID(categoryID,categoryrenameJson);
expect(apicategory).to.have.status(200);
console.log("Rename category successfully executed");
}
catch (e)
{
console.log("Failed to Rename category");
throw e;
}
});

//Delete Category API
test.skip('Delete Category API', async()=> {
jest.setTimeout(20000);
try {
console.log("Delete Created Cateory");
console.log("Running delete category and attemptin to delete ::: " + categoryID);
const apicategory = await api.deleteTeamCategoriesWithCategoryID(categoryID);
expect(apicategory).to.have.status(200);
console.log("Delete category successfully executed");
}
catch (e)
{
console.log("Failed to delete category");
throw e;
}
});

});

teamCategory.js 的单独 Json 函数 文件名 ApiCategory.js

class ApiCategory {

constructor()
{
//super();
}

generateCreateCategoryJsonObject(categoryName,groupID) {

return{
"name": categoryName,
"groupId": groupID, //if you pass manually groupId here and run the code then code is executed successfully.
"parent": 0

}
}

renameCreateCategoryJsonObject(categoryName_rename) {

return{
"name": categoryName_rename
}

}

}
module.exports = ApiCategory;

最佳答案

一个简单的 pub sub 模块可能会对您有所帮助

const topics = {};
const hOP = topics.hasOwnProperty;

export default class Events {
/**
*
* @param topic
* @param listener
* @returns {{remove: remove}}
*/
subscribe(topic, listener) {
if (!hOP.call(topics, topic)) topics[topic] = [];
const index = topics[topic].push(listener) - 1;

return {
remove: function() {
delete topics[topic][index];
}
};
}

/**
*
* @param topic
* @param info
*/
publish(topic, info) {
if (!hOP.call(topics, topic)) return;

topics[topic].forEach(function(item) {
item(info != undefined ? info : {});
});
}

}

在某个地方的 js 文件中创建它。然后将其导入到每个 js 文件中。当您想要将值从一个脚本传递到另一个脚本时,您可以首先在 teamgroupapi 文件中发布并在 teamCategoryApi 文件中订阅事件。

self.events.publish('/eventId', groupId);

events.subscribe('/eventId', (groupId) => {
console.log(groupId);
// do stuff
});

关于javascript - 如何将动态 `groupID`从一个js文件传递到另一个js文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48766135/

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