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

时间:2018-02-13 11:47:39

标签: javascript ecmascript-6 jestjs

我附上了我的代码以供参考,我希望将动态 groupID teamgroupapi.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文件名ApiGroup.js

分隔Json函数
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文件名ApiCategory.js

分隔Json函数
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; 

2 个答案:

答案 0 :(得分:1)

一个简单的pub子模块可能会帮助你

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
        });

答案 1 :(得分:0)

将此行添加到teamgroupapi.js文件

后问题就解决了
export let groupID;
exports.groupID = 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-slurmhourly.hourly.cc.altus.bblabs/documentation/api.yaml';
const token = process.env.BENDER_LOGIN_TOKEN || 'ju7WkQItxRMFdMtghlGEVz5CZdC1b4umwLId16591CbK00hWs1a1_lT63cBr8xkvBhPK_vWO-fJTUBdP99LFVw';
console.log(`login token is ${token}`);
const apiUrl = 'https://' + (process.env.CC_URL_API || 'api-slurmhourly.hourly.cc.altus.bblabs');

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

export var groupID;

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

  let api;
  let apiGroup;
  //let groupID;
  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 groupJson = apiGroup.generateCreateGroupJsonObject(groupName);
      const createGroup = await api.postTeamGroups(groupJson);
      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);
      const getGroup = await api.getTeamGroups(false,false);
      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;     
    }
  });
});
exports.groupID = groupID;

teamCategoryApi.js文件中添加以下两行。

var teamgroupapi = require('./teamgroupapi.js');
groupID = teamgroupapi.groupID;

teamCategoryApi.js文件中添加以上两行之后,问题就会得到解决。

import { getGeneratedApi } from '@test/bender-executor-simple-api-generator';
import ApiCategory from '../_support/ApiCategory.js';
var teamgroupapi = require('./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-slurmhourly.hourly.cc.altus.bblabs/documentation/api.json';
const token = process.env.BENDER_LOGIN_TOKEN || 'ju7WkQItxRMFdMtghlGEVz5CZdC1b4umwLId16591CbK00hWs1a1_lT63cBr8xkvBhPK_vWO-fJTUBdP99LFVw';
console.log(`login token is ${token}`);
const apiUrl = 'https://' + (process.env.CC_URL_API || 'api-slurmhourly.hourly.cc.altus.bblabs');

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");
      groupID = teamgroupapi.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('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('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('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;
    }
  });
});