Best JavaScript code snippet using wpt
api_spec.js
Source:api_spec.js  
1import MockAdapter from 'axios-mock-adapter';2import Api from 'ee/api';3import * as cycleAnalyticsConstants from 'ee/analytics/cycle_analytics/constants';4import axios from '~/lib/utils/axios_utils';5import httpStatus from '~/lib/utils/http_status';6import * as analyticsMockData from 'ee_jest/analytics/cycle_analytics/mock_data';7describe('Api', () => {8  const dummyApiVersion = 'v3000';9  const dummyUrlRoot = '/gitlab';10  const dummyGon = {11    api_version: dummyApiVersion,12    relative_url_root: dummyUrlRoot,13  };14  const mockEpics = [15    {16      id: 1,17      iid: 10,18      group_id: 2,19      title: 'foo',20    },21    {22      id: 2,23      iid: 11,24      group_id: 2,25      title: 'bar',26    },27  ];28  let originalGon;29  let mock;30  beforeEach(() => {31    mock = new MockAdapter(axios);32    originalGon = window.gon;33    window.gon = { ...dummyGon };34  });35  afterEach(() => {36    mock.restore();37    window.gon = originalGon;38  });39  describe('ldapGroups', () => {40    it('calls callback on completion', done => {41      const query = 'query';42      const provider = 'provider';43      const callback = jest.fn();44      const expectedUrl = `${dummyUrlRoot}/api/${dummyApiVersion}/ldap/${provider}/groups.json`;45      mock.onGet(expectedUrl).reply(200, [46        {47          name: 'test',48        },49      ]);50      Api.ldapGroups(query, provider, callback)51        .then(response => {52          expect(callback).toHaveBeenCalledWith(response);53        })54        .then(done)55        .catch(done.fail);56    });57  });58  describe('createChildEpic', () => {59    it('calls `axios.post` using params `groupId`, `parentEpicIid` and title', done => {60      const groupId = 'gitlab-org';61      const parentEpicIid = 1;62      const title = 'Sample epic';63      const expectedUrl = `${dummyUrlRoot}/api/${dummyApiVersion}/groups/${groupId}/epics/${parentEpicIid}/epics`;64      const expectedRes = {65        title,66        id: 20,67        iid: 5,68      };69      mock.onPost(expectedUrl).reply(200, expectedRes);70      Api.createChildEpic({ groupId, parentEpicIid, title })71        .then(({ data }) => {72          expect(data.title).toBe(expectedRes.title);73          expect(data.id).toBe(expectedRes.id);74          expect(data.iid).toBe(expectedRes.iid);75        })76        .then(done)77        .catch(done.fail);78    });79  });80  describe('groupEpics', () => {81    it('calls `axios.get` using param `groupId`', done => {82      const groupId = 2;83      const expectedUrl = `${dummyUrlRoot}/api/${dummyApiVersion}/groups/${groupId}/epics`;84      mock85        .onGet(expectedUrl, {86          params: {87            include_ancestor_groups: false,88            include_descendant_groups: true,89          },90        })91        .reply(200, mockEpics);92      Api.groupEpics({ groupId })93        .then(({ data }) => {94          data.forEach((epic, index) => {95            expect(epic.id).toBe(mockEpics[index].id);96            expect(epic.iid).toBe(mockEpics[index].iid);97            expect(epic.group_id).toBe(mockEpics[index].group_id);98            expect(epic.title).toBe(mockEpics[index].title);99          });100        })101        .then(done)102        .catch(done.fail);103    });104    it('calls `axios.get` using param `search` when it is provided', done => {105      const groupId = 2;106      const expectedUrl = `${dummyUrlRoot}/api/${dummyApiVersion}/groups/${groupId}/epics`;107      mock108        .onGet(expectedUrl, {109          params: {110            include_ancestor_groups: false,111            include_descendant_groups: true,112            search: 'foo',113          },114        })115        .reply(200, mockEpics);116      Api.groupEpics({ groupId, search: 'foo' })117        .then(({ data }) => {118          data.forEach((epic, index) => {119            expect(epic.id).toBe(mockEpics[index].id);120            expect(epic.iid).toBe(mockEpics[index].iid);121            expect(epic.group_id).toBe(mockEpics[index].group_id);122            expect(epic.title).toBe(mockEpics[index].title);123          });124        })125        .then(done)126        .catch(done.fail);127    });128  });129  describe('addEpicIssue', () => {130    it('calls `axios.post` using params `groupId`, `epicIid` and `issueId`', done => {131      const groupId = 2;132      const mockIssue = {133        id: 20,134      };135      const expectedUrl = `${dummyUrlRoot}/api/${dummyApiVersion}/groups/${groupId}/epics/${mockEpics[0].iid}/issues/${mockIssue.id}`;136      const expectedRes = {137        id: 30,138        epic: mockEpics[0],139        issue: mockIssue,140      };141      mock.onPost(expectedUrl).reply(200, expectedRes);142      Api.addEpicIssue({ groupId, epicIid: mockEpics[0].iid, issueId: mockIssue.id })143        .then(({ data }) => {144          expect(data.id).toBe(expectedRes.id);145          expect(data.epic).toEqual(expect.objectContaining({ ...expectedRes.epic }));146          expect(data.issue).toEqual(expect.objectContaining({ ...expectedRes.issue }));147        })148        .then(done)149        .catch(done.fail);150    });151  });152  describe('removeEpicIssue', () => {153    it('calls `axios.delete` using params `groupId`, `epicIid` and `epicIssueId`', done => {154      const groupId = 2;155      const mockIssue = {156        id: 20,157        epic_issue_id: 40,158      };159      const expectedUrl = `${dummyUrlRoot}/api/${dummyApiVersion}/groups/${groupId}/epics/${mockEpics[0].iid}/issues/${mockIssue.epic_issue_id}`;160      const expectedRes = {161        id: 30,162        epic: mockEpics[0],163        issue: mockIssue,164      };165      mock.onDelete(expectedUrl).reply(200, expectedRes);166      Api.removeEpicIssue({167        groupId,168        epicIid: mockEpics[0].iid,169        epicIssueId: mockIssue.epic_issue_id,170      })171        .then(({ data }) => {172          expect(data.id).toBe(expectedRes.id);173          expect(data.epic).toEqual(expect.objectContaining({ ...expectedRes.epic }));174          expect(data.issue).toEqual(expect.objectContaining({ ...expectedRes.issue }));175        })176        .then(done)177        .catch(done.fail);178    });179  });180  describe('packages', () => {181    const projectId = 'project_a';182    const packageId = 'package_b';183    const apiResponse = [{ id: 1, name: 'foo' }];184    describe('groupPackages', () => {185      const groupId = 'group_a';186      it('fetch all group packages', () => {187        const expectedUrl = `${dummyUrlRoot}/api/${dummyApiVersion}/groups/${groupId}/packages`;188        jest.spyOn(axios, 'get');189        mock.onGet(expectedUrl).replyOnce(200, apiResponse);190        return Api.groupPackages(groupId).then(({ data }) => {191          expect(data).toEqual(apiResponse);192          expect(axios.get).toHaveBeenCalledWith(expectedUrl, {});193        });194      });195    });196    describe('projectPackages', () => {197      it('fetch all project packages', () => {198        const expectedUrl = `${dummyUrlRoot}/api/${dummyApiVersion}/projects/${projectId}/packages`;199        jest.spyOn(axios, 'get');200        mock.onGet(expectedUrl).replyOnce(200, apiResponse);201        return Api.projectPackages(projectId).then(({ data }) => {202          expect(data).toEqual(apiResponse);203          expect(axios.get).toHaveBeenCalledWith(expectedUrl, {});204        });205      });206    });207    describe('buildProjectPackageUrl', () => {208      it('returns the right url', () => {209        const expectedUrl = `${dummyUrlRoot}/api/${dummyApiVersion}/projects/${projectId}/packages/${packageId}`;210        const url = Api.buildProjectPackageUrl(projectId, packageId);211        expect(url).toEqual(expectedUrl);212      });213    });214    describe('projectPackage', () => {215      it('fetch package details', () => {216        const expectedUrl = `foo`;217        jest.spyOn(Api, 'buildProjectPackageUrl').mockReturnValue(expectedUrl);218        jest.spyOn(axios, 'get');219        mock.onGet(expectedUrl).replyOnce(200, apiResponse);220        return Api.projectPackage(projectId, packageId).then(({ data }) => {221          expect(data).toEqual(apiResponse);222          expect(axios.get).toHaveBeenCalledWith(expectedUrl);223        });224      });225    });226    describe('deleteProjectPackage', () => {227      it('delete a package', () => {228        const expectedUrl = `foo`;229        jest.spyOn(Api, 'buildProjectPackageUrl').mockReturnValue(expectedUrl);230        jest.spyOn(axios, 'delete');231        mock.onDelete(expectedUrl).replyOnce(200, true);232        return Api.deleteProjectPackage(projectId, packageId).then(({ data }) => {233          expect(data).toEqual(true);234          expect(axios.delete).toHaveBeenCalledWith(expectedUrl);235        });236      });237    });238  });239  describe('Cycle analytics', () => {240    const groupId = 'counting-54321';241    const createdBefore = '2019-11-18';242    const createdAfter = '2019-08-18';243    const stageId = 'thursday';244    const dummyCycleAnalyticsUrlRoot = `${dummyUrlRoot}/groups/${groupId}`;245    const defaultParams = {246      created_after: createdAfter,247      created_before: createdBefore,248    };249    const expectRequestWithCorrectParameters = (responseObj, { params, expectedUrl, response }) => {250      const {251        data,252        config: { params: reqParams, url },253      } = responseObj;254      expect(data).toEqual(response);255      expect(reqParams).toEqual(params);256      expect(url).toEqual(expectedUrl);257    };258    describe('cycleAnalyticsTasksByType', () => {259      it('fetches tasks by type data', done => {260        const tasksByTypeResponse = [261          {262            label: {263              id: 9,264              title: 'Thursday',265              color: '#7F8C8D',266              description: 'What are you waiting for?',267              group_id: 2,268              project_id: null,269              template: false,270              text_color: '#FFFFFF',271              created_at: '2019-08-20T05:22:49.046Z',272              updated_at: '2019-08-20T05:22:49.046Z',273            },274            series: [['2019-11-03', 5]],275          },276        ];277        const labelIds = [10, 9, 8, 7];278        const params = {279          ...defaultParams,280          project_ids: null,281          subject: cycleAnalyticsConstants.TASKS_BY_TYPE_SUBJECT_ISSUE,282          label_ids: labelIds,283        };284        const expectedUrl = analyticsMockData.endpoints.tasksByTypeData;285        mock.onGet(expectedUrl).reply(200, tasksByTypeResponse);286        Api.cycleAnalyticsTasksByType(groupId, params)287          .then(({ data, config: { params: reqParams } }) => {288            expect(data).toEqual(tasksByTypeResponse);289            expect(reqParams).toEqual(params);290          })291          .then(done)292          .catch(done.fail);293      });294    });295    describe('cycleAnalyticsTopLabels', () => {296      it('fetches top group level labels', done => {297        const response = [];298        const labelIds = [10, 9, 8, 7];299        const params = {300          ...defaultParams,301          project_ids: null,302          subject: cycleAnalyticsConstants.TASKS_BY_TYPE_SUBJECT_ISSUE,303          label_ids: labelIds,304        };305        const expectedUrl = analyticsMockData.endpoints.tasksByTypeTopLabelsData;306        mock.onGet(expectedUrl).reply(200, response);307        Api.cycleAnalyticsTopLabels(groupId, params)308          .then(({ data, config: { url, params: reqParams } }) => {309            expect(data).toEqual(response);310            expect(url).toMatch(expectedUrl);311            expect(reqParams).toEqual(params);312          })313          .then(done)314          .catch(done.fail);315      });316    });317    describe('cycleAnalyticsSummaryData', () => {318      it('fetches value stream analytics summary data', done => {319        const response = [{ value: 0, title: 'New Issues' }, { value: 0, title: 'Deploys' }];320        const params = {321          ...defaultParams,322        };323        const expectedUrl = `${dummyCycleAnalyticsUrlRoot}/-/analytics/value_stream_analytics/summary`;324        mock.onGet(expectedUrl).reply(200, response);325        Api.cycleAnalyticsSummaryData(groupId, params)326          .then(responseObj =>327            expectRequestWithCorrectParameters(responseObj, {328              response,329              params,330              expectedUrl,331            }),332          )333          .then(done)334          .catch(done.fail);335      });336    });337    describe('cycleAnalyticsTimeSummaryData', () => {338      it('fetches value stream analytics summary data', done => {339        const response = [340          { value: '10.0', title: 'Lead time', unit: 'per day' },341          { value: '2.0', title: 'Cycle Time', unit: 'per day' },342        ];343        const params = {344          ...defaultParams,345        };346        const expectedUrl = `${dummyCycleAnalyticsUrlRoot}/-/analytics/value_stream_analytics/time_summary`;347        mock.onGet(expectedUrl).reply(200, response);348        Api.cycleAnalyticsTimeSummaryData(groupId, params)349          .then(responseObj =>350            expectRequestWithCorrectParameters(responseObj, {351              response,352              params,353              expectedUrl,354            }),355          )356          .then(done)357          .catch(done.fail);358      });359    });360    describe('cycleAnalyticsGroupStagesAndEvents', () => {361      it('fetches custom stage events and all stages', done => {362        const response = { events: [], stages: [] };363        const params = {364          group_id: groupId,365          'cycle_analytics[created_after]': createdAfter,366          'cycle_analytics[created_before]': createdBefore,367        };368        const expectedUrl = `${dummyCycleAnalyticsUrlRoot}/-/analytics/value_stream_analytics/stages`;369        mock.onGet(expectedUrl).reply(200, response);370        Api.cycleAnalyticsGroupStagesAndEvents(groupId, params)371          .then(responseObj =>372            expectRequestWithCorrectParameters(responseObj, {373              response,374              params,375              expectedUrl,376            }),377          )378          .then(done)379          .catch(done.fail);380      });381    });382    describe('cycleAnalyticsStageEvents', () => {383      it('fetches stage events', done => {384        const response = { events: [] };385        const params = {386          ...defaultParams,387        };388        const expectedUrl = `${dummyCycleAnalyticsUrlRoot}/-/analytics/value_stream_analytics/stages/${stageId}/records`;389        mock.onGet(expectedUrl).reply(200, response);390        Api.cycleAnalyticsStageEvents(groupId, stageId, params)391          .then(responseObj =>392            expectRequestWithCorrectParameters(responseObj, {393              response,394              params,395              expectedUrl,396            }),397          )398          .then(done)399          .catch(done.fail);400      });401    });402    describe('cycleAnalyticsStageMedian', () => {403      it('fetches stage events', done => {404        const response = { value: '5 days ago' };405        const params = {406          ...defaultParams,407        };408        const expectedUrl = `${dummyCycleAnalyticsUrlRoot}/-/analytics/value_stream_analytics/stages/${stageId}/median`;409        mock.onGet(expectedUrl).reply(200, response);410        Api.cycleAnalyticsStageMedian(groupId, stageId, params)411          .then(responseObj =>412            expectRequestWithCorrectParameters(responseObj, {413              response,414              params,415              expectedUrl,416            }),417          )418          .then(done)419          .catch(done.fail);420      });421    });422    describe('cycleAnalyticsCreateStage', () => {423      it('submit the custom stage data', done => {424        const response = {};425        const customStage = {426          name: 'cool-stage',427          start_event_identifier: 'issue_created',428          start_event_label_id: null,429          end_event_identifier: 'issue_closed',430          end_event_label_id: null,431        };432        const expectedUrl = `${dummyCycleAnalyticsUrlRoot}/-/analytics/value_stream_analytics/stages`;433        mock.onPost(expectedUrl).reply(200, response);434        Api.cycleAnalyticsCreateStage(groupId, customStage)435          .then(({ data, config: { data: reqData, url } }) => {436            expect(data).toEqual(response);437            expect(JSON.parse(reqData)).toMatchObject(customStage);438            expect(url).toEqual(expectedUrl);439          })440          .then(done)441          .catch(done.fail);442      });443    });444    describe('cycleAnalyticsUpdateStage', () => {445      it('updates the stage data', done => {446        const response = { id: stageId, custom: false, hidden: true, name: 'nice-stage' };447        const stageData = {448          name: 'nice-stage',449          hidden: true,450        };451        const expectedUrl = `${dummyCycleAnalyticsUrlRoot}/-/analytics/value_stream_analytics/stages/${stageId}`;452        mock.onPut(expectedUrl).reply(200, response);453        Api.cycleAnalyticsUpdateStage(stageId, groupId, stageData)454          .then(({ data, config: { data: reqData, url } }) => {455            expect(data).toEqual(response);456            expect(JSON.parse(reqData)).toMatchObject(stageData);457            expect(url).toEqual(expectedUrl);458          })459          .then(done)460          .catch(done.fail);461      });462    });463    describe('cycleAnalyticsRemoveStage', () => {464      it('deletes the specified data', done => {465        const response = { id: stageId, hidden: true, custom: true };466        const expectedUrl = `${dummyCycleAnalyticsUrlRoot}/-/analytics/value_stream_analytics/stages/${stageId}`;467        mock.onDelete(expectedUrl).reply(200, response);468        Api.cycleAnalyticsRemoveStage(stageId, groupId)469          .then(({ data, config: { url } }) => {470            expect(data).toEqual(response);471            expect(url).toEqual(expectedUrl);472          })473          .then(done)474          .catch(done.fail);475      });476    });477    describe('cycleAnalyticsDurationChart', () => {478      it('fetches stage duration data', done => {479        const response = [];480        const params = {481          ...defaultParams,482        };483        const expectedUrl = `${dummyCycleAnalyticsUrlRoot}/-/analytics/value_stream_analytics/stages/thursday/duration_chart`;484        mock.onGet(expectedUrl).reply(200, response);485        Api.cycleAnalyticsDurationChart(groupId, stageId, params)486          .then(responseObj =>487            expectRequestWithCorrectParameters(responseObj, {488              response,489              params,490              expectedUrl,491            }),492          )493          .then(done)494          .catch(done.fail);495      });496    });497    describe('cycleAnalyticsGroupLabels', () => {498      it('fetches group level labels', done => {499        const response = [];500        const expectedUrl = `${dummyUrlRoot}/groups/${groupId}/-/labels.json`;501        mock.onGet(expectedUrl).reply(httpStatus.OK, response);502        Api.cycleAnalyticsGroupLabels(groupId)503          .then(({ data, config: { url } }) => {504            expect(data).toEqual(response);505            expect(url).toEqual(expectedUrl);506          })507          .then(done)508          .catch(done.fail);509      });510    });511  });512  describe('GroupActivityAnalytics', () => {513    const groupId = 'gitlab-org';514    describe('groupActivityMergeRequestsCount', () => {515      it('fetches the number of MRs created for a given group', () => {516        const response = { merge_requests_count: 10 };517        const expectedUrl = `${dummyUrlRoot}/api/${dummyApiVersion}/analytics/group_activity/merge_requests_count`;518        jest.spyOn(Api, 'buildUrl').mockReturnValue(expectedUrl);519        jest.spyOn(axios, 'get');520        mock.onGet(expectedUrl).reply(200, response);521        return Api.groupActivityMergeRequestsCount(groupId).then(({ data }) => {522          expect(data).toEqual(response);523          expect(axios.get).toHaveBeenCalledWith(expectedUrl, { params: { group_path: groupId } });524        });525      });526    });527    describe('groupActivityIssuesCount', () => {528      it('fetches the number of issues created for a given group', () => {529        const response = { issues_count: 20 };530        const expectedUrl = `${dummyUrlRoot}/api/${dummyApiVersion}/analytics/group_activity/issues_count`;531        jest.spyOn(Api, 'buildUrl').mockReturnValue(expectedUrl);532        jest.spyOn(axios, 'get');533        mock.onGet(expectedUrl).replyOnce(200, response);534        return Api.groupActivityIssuesCount(groupId).then(({ data }) => {535          expect(data).toEqual(response);536          expect(axios.get).toHaveBeenCalledWith(expectedUrl, { params: { group_path: groupId } });537        });538      });539    });540    describe('groupActivityNewMembersCount', () => {541      it('fetches the number of new members created for a given group', () => {542        const response = { new_members_count: 30 };543        const expectedUrl = `${dummyUrlRoot}/api/${dummyApiVersion}/analytics/group_activity/new_members_count`;544        jest.spyOn(Api, 'buildUrl').mockReturnValue(expectedUrl);545        jest.spyOn(axios, 'get');546        mock.onGet(expectedUrl).reply(200, response);547        return Api.groupActivityNewMembersCount(groupId).then(({ data }) => {548          expect(data).toEqual(response);549          expect(axios.get).toHaveBeenCalledWith(expectedUrl, { params: { group_path: groupId } });550        });551      });552    });553  });554  describe('GeoReplicable', () => {555    let expectedUrl;556    let apiResponse;557    let mockParams;558    let mockReplicableType;559    beforeEach(() => {560      mockReplicableType = 'designs';561      expectedUrl = `${dummyUrlRoot}/api/${dummyApiVersion}/geo_replication/${mockReplicableType}`;562    });563    describe('getGeoReplicableItems', () => {564      it('fetches replicableItems based on replicableType', () => {565        apiResponse = [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }];566        mockParams = { page: 1 };567        jest.spyOn(Api, 'buildUrl').mockReturnValue(expectedUrl);568        jest.spyOn(axios, 'get');569        mock.onGet(expectedUrl).replyOnce(200, apiResponse);570        return Api.getGeoReplicableItems(mockReplicableType, mockParams).then(({ data }) => {571          expect(data).toEqual(apiResponse);572          expect(axios.get).toHaveBeenCalledWith(expectedUrl, { params: mockParams });573        });574      });575    });576    describe('initiateAllGeoReplicableSyncs', () => {577      it('POSTs with correct action', () => {578        apiResponse = [{ status: 'ok' }];579        mockParams = {};580        const mockAction = 'reverify';581        jest.spyOn(Api, 'buildUrl').mockReturnValue(expectedUrl);582        jest.spyOn(axios, 'post');583        mock.onPost(`${expectedUrl}/${mockAction}`).replyOnce(201, apiResponse);584        return Api.initiateAllGeoReplicableSyncs(mockReplicableType, mockAction).then(585          ({ data }) => {586            expect(data).toEqual(apiResponse);587            expect(axios.post).toHaveBeenCalledWith(`${expectedUrl}/${mockAction}`, mockParams);588          },589        );590      });591    });592    describe('initiateGeoReplicableSync', () => {593      it('PUTs with correct action and projectId', () => {594        apiResponse = [{ status: 'ok' }];595        mockParams = {};596        const mockAction = 'reverify';597        const mockProjectId = 1;598        jest.spyOn(Api, 'buildUrl').mockReturnValue(expectedUrl);599        jest.spyOn(axios, 'put');600        mock.onPut(`${expectedUrl}/${mockProjectId}/${mockAction}`).replyOnce(201, apiResponse);601        return Api.initiateGeoReplicableSync(mockReplicableType, {602          projectId: mockProjectId,603          action: mockAction,604        }).then(({ data }) => {605          expect(data).toEqual(apiResponse);606          expect(axios.put).toHaveBeenCalledWith(607            `${expectedUrl}/${mockProjectId}/${mockAction}`,608            mockParams,609          );610        });611      });612    });613  });614  describe('changeVulnerabilityState', () => {615    it.each`616      id    | action617      ${5}  | ${'dismiss'}618      ${7}  | ${'confirm'}619      ${38} | ${'resolve'}620    `('POSTS to correct endpoint ($id, $action)', ({ id, action }) => {621      const expectedUrl = `${dummyUrlRoot}/api/${dummyApiVersion}/vulnerabilities/${id}/${action}`;622      const expectedResponse = { id, action, test: 'test' };623      mock.onPost(expectedUrl).replyOnce(200, expectedResponse);624      return Api.changeVulnerabilityState(id, action).then(({ data }) => {625        expect(mock.history.post).toContainEqual(expect.objectContaining({ url: expectedUrl }));626        expect(data).toEqual(expectedResponse);627      });628    });629  });630  describe('GeoNode', () => {631    let expectedUrl;632    let mockNode;633    beforeEach(() => {634      expectedUrl = `${dummyUrlRoot}/api/${dummyApiVersion}/geo_nodes`;635    });636    describe('createGeoNode', () => {637      it('POSTs with correct action', () => {638        mockNode = {639          name: 'Mock Node',640          url: 'https://mock_node.gitlab.com',641          primary: false,642        };643        jest.spyOn(Api, 'buildUrl').mockReturnValue(expectedUrl);644        jest.spyOn(axios, 'post');645        mock.onPost(expectedUrl).replyOnce(201, mockNode);646        return Api.createGeoNode(mockNode).then(({ data }) => {647          expect(data).toEqual(mockNode);648          expect(axios.post).toHaveBeenCalledWith(expectedUrl, mockNode);649        });650      });651    });652    describe('updateGeoNode', () => {653      it('PUTs with correct action', () => {654        mockNode = {655          id: 1,656          name: 'Mock Node',657          url: 'https://mock_node.gitlab.com',658          primary: false,659        };660        jest.spyOn(Api, 'buildUrl').mockReturnValue(expectedUrl);661        jest.spyOn(axios, 'put');662        mock.onPut(`${expectedUrl}/${mockNode.id}`).replyOnce(201, mockNode);663        return Api.updateGeoNode(mockNode).then(({ data }) => {664          expect(data).toEqual(mockNode);665          expect(axios.put).toHaveBeenCalledWith(`${expectedUrl}/${mockNode.id}`, mockNode);666        });667      });668    });669  });670  describe('Feature Flag User List', () => {671    let expectedUrl;672    let projectId;673    let mockUserList;674    beforeEach(() => {675      projectId = 1000;676      expectedUrl = `${dummyUrlRoot}/api/${dummyApiVersion}/projects/${projectId}/feature_flags_user_lists`;677      mockUserList = {678        name: 'mock_user_list',679        user_xids: '1,2,3,4',680        project_id: 1,681        id: 1,682        iid: 1,683      };684    });685    describe('fetchFeatureFlagUserLists', () => {686      it('GETs the right url', () => {687        mock.onGet(expectedUrl).replyOnce(200, []);688        return Api.fetchFeatureFlagUserLists(dummyApiVersion, projectId).then(({ data }) => {689          expect(data).toEqual([]);690        });691      });692    });693    describe('createFeatureFlagUserList', () => {694      it('POSTs data to the right url', () => {695        const mockUserListData = {696          name: 'mock_user_list',697          user_xids: '1,2,3,4',698        };699        mock.onPost(expectedUrl, mockUserListData).replyOnce(200, mockUserList);700        return Api.createFeatureFlagUserList(dummyApiVersion, projectId, mockUserListData).then(701          ({ data }) => {702            expect(data).toEqual(mockUserList);703          },704        );705      });706    });707    describe('fetchFeatureFlagUserList', () => {708      it('GETs the right url', () => {709        mock.onGet(`${expectedUrl}/1`).replyOnce(200, mockUserList);710        return Api.fetchFeatureFlagUserList(dummyApiVersion, projectId, 1).then(({ data }) => {711          expect(data).toEqual(mockUserList);712        });713      });714    });715    describe('updateFeatureFlagUserList', () => {716      it('PUTs the right url', () => {717        mock.onPut(`${expectedUrl}/1`).replyOnce(200, { ...mockUserList, user_xids: '5' });718        return Api.updateFeatureFlagUserList(dummyApiVersion, projectId, {719          ...mockUserList,720          user_xids: '5',721        }).then(({ data }) => {722          expect(data).toEqual({ ...mockUserList, user_xids: '5' });723        });724      });725    });726    describe('deleteFeatureFlagUserList', () => {727      it('DELETEs the right url', () => {728        mock.onDelete(`${expectedUrl}/1`).replyOnce(200, 'deleted');729        return Api.deleteFeatureFlagUserList(dummyApiVersion, projectId, 1).then(({ data }) => {730          expect(data).toBe('deleted');731        });732      });733    });734  });...footer.helper.ts
Source:footer.helper.ts  
1import { commonPageObjects } from "../../../common/common.po";2import { browser } from "protractor";3import { ChallengeListingPageHelper } from "../challenge-listing/challenge-listing.helper";4import { FooterConstants } from "./footer.constants";5import { commonPageHelper } from "../../../common/common.helper";6export class FooterHelper {7    static async verifyFooterLinks() {8        const linksConfig = [9            {10                label: 'ABOUT US',11                expectedUrl: FooterConstants.content.aboutUrl12            },13            {14                label: 'CONTACT US',15                expectedUrl: FooterConstants.content.contactUrl16            },17            {18                label: 'HELP CENTER',19                expectedUrl: FooterConstants.content.helpUrl20            },21            {22                label: 'PRIVACY POLICY',23                expectedUrl: FooterConstants.content.privacyUrl24            },25            {26                label: 'TERMS',27                expectedUrl: FooterConstants.content.termsUrl28            }29        ];30        for (let i = 0; i < linksConfig.length; i++) {31            const linkConfig = linksConfig[i];32            await this.verifyLink(linkConfig.label, linkConfig.expectedUrl);33            await ChallengeListingPageHelper.get();34        }35    }36    static async verifyLink(label: string, expectedUrl: string) {37        await commonPageObjects.findElementByText('a', label).click();38        await browser.wait(async () => {39            const url = await browser.getCurrentUrl();40            return url === expectedUrl;41        });42    }43    static async verifySocialIcons() {44        const linksConfig = [45            {46                label: 'Facebook',47                expectedUrl: FooterConstants.content.fbUrl48            },49            {50                label: 'Twitter',51                expectedUrl: FooterConstants.content.twitterUrl52            },53            {54                label: 'Linkedin',55                expectedUrl: FooterConstants.content.linkedInUrl56            },57            {58                label: 'Instagram',59                expectedUrl: FooterConstants.content.instagramUrl60            }61        ];62        for (let i = 0; i < linksConfig.length; i++) {63            const linkConfig = linksConfig[i];64            await this.verifySocialLink(linkConfig.label, linkConfig.expectedUrl);65        }66    }67    static async verifySocialLink(label: string, expectedUrl: string) {68        await commonPageObjects.getLinkByAriaLabel(label).click();69        if (label === 'Linkedin') {70            // specifically checking differently for linkedin since Linkedin url doesn't always land on the topcoder profile page as it detects that Selenium web-driver is running and hence  shows some verification page71            await commonPageHelper.verifyPopupWindow();72        } else {73            await commonPageHelper.verifyPopupWindowWithUrl(expectedUrl);74        }75    }...Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3  if (err) return console.error(err);4  wpt.getTestResults(data.data.testId, function(err, data) {5    if (err) return console.error(err);6    console.log(data.data.runs[1].firstView);7  });8});9var wpt = require('webpagetest');10var wpt = new WebPageTest('www.webpagetest.org');11  if (err) return console.error(err);12  wpt.getTestResults(data.data.testId, function(err, data) {13    if (err) return console.error(err);14    console.log(data.data.runs[1].firstView);15  });16});Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3  if (err) return console.error(err);4  wpt.getTestResults(data.data.testId, function(err, data) {5    if (err) return console.error(err);6    var url = wpt.expectedURL(data.data.testId);7    console.log(url);8  });9});Using AI Code Generation
1var webdriver = require('selenium-webdriver'),2    until = webdriver.until;3var wpt = require('webpagetest');4var wpt = new WebPageTest('www.webpagetest.org', 'A.7a8a53b9f7a4ad4b4d7f4c4a2a4a4a4a');5var driver = new webdriver.Builder()6    .forBrowser('firefox')7    .build();8driver.getTitle().then(function(title) {9    console.log("title is: " + title);10});11driver.getCurrentUrl().then(function(url) {12    console.log("url is: " + url);13});14driver.getPageSource().then(function(source) {15    console.log("source is: " + source);16});17driver.quit();18  if (err) return console.error(err);19  console.log('Test status:', data.statusText);20  console.log('Test ID:', data.data.testId);21  console.log('Test URL:', data.data.summary);22});23  if (err) return console.error(err);24  console.log('Test status:', data.statusText);25  console.log('Test ID:', data.data.testId);26  console.log('Test URL:', data.data.summary);27});28  if (err) return console.error(err);29  console.log('Test status:', data.statusText);30  console.log('Test ID:', data.data.testId);31  console.log('Test URL:', data.data.summary);32  console.log('Test firstView:', data.data.median.firstView);33  console.log('Test repeatView:', data.data.median.repeatView);34});35  if (err) return console.error(err);36  console.log('Test status:', data.statusText);37  console.log('Test ID:', data.dataUsing AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3    if (err) return console.error(err);4    wpt.getTestResults(data.data.testId, function(err, data) {5        if (err) return console.error(err);6        console.log(data.data.runs[1].firstView);7    });8});9var wpt = require('webpagetest');10var wpt = new WebPageTest('www.webpagetest.org');11    if (err) return console.error(err);12    wpt.getTestResults(data.data.testId, function(err, data) {13        if (err) return console.error(err);14        console.log(data.data.runs[1].firstView);15    });16});17var wpt = require('webpagetest');18var wpt = new WebPageTest('www.webpagetest.org');19    if (err) return console.error(err);20    wpt.getTestResults(data.data.testId, function(err, data) {21        if (err) return console.error(err);22        console.log(data.data.runs[1].firstView);23    });24});25var wpt = require('webpagetest');26var wpt = new WebPageTest('www.webpagetest.org');27    if (err) return console.error(err);28    wpt.getTestResults(data.data.testId, function(err, data) {29        if (err) return console.error(errUsing AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'A.1234567890abcdef1234567890abcdef');3wpt.runTest(url, function(err, data) {4  if (err) return console.error(err);5  wpt.getTestResults(data.data.testId, function(err, data) {6    if (err) return console.error(err);7    console.log(data);8  });9});10The example code is using the WebPageTest class directly.  You are creating a new WebPageTest object and then assigning that to the wpt variable.  You need to remove the second line (var wpt = new WebPageTest('www.webpagetest.org', 'A.1234567890abcdef1234567890abcdef');) and just use theLearn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
