Best JavaScript code snippet using cypress
actions.test.js
Source:actions.test.js
1/*2 * Copyright (c) Enalean, 2018-Present. All Rights Reserved.3 *4 * This file is a part of Tuleap.5 *6 * Tuleap is free software; you can redistribute it and/or modify7 * it under the terms of the GNU General Public License as published by8 * the Free Software Foundation; either version 2 of the License, or9 * (at your option) any later version.10 *11 * Tuleap is distributed in the hope that it will be useful,12 * but WITHOUT ANY WARRANTY; without even the implied warranty of13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the14 * GNU General Public License for more details.15 *16 * You should have received a copy of the GNU General Public License17 * along with Tuleap. If not, see <http://www.gnu.org/licenses/>.18 */19import * as actions from "./actions.js";20import * as rest_querier from "../api/rest-querier.js";21import * as window_helper from "../helpers/window-helper.js";22describe("Store actions", () => {23 let context;24 beforeEach(() => {25 context = {26 commit: jest.fn(),27 };28 });29 describe("init", () => {30 it("loads branches of current repository and store them as source branches", async () => {31 const branches = [{ name: "master" }, { name: "feature/branch" }];32 const getBranches = jest.spyOn(rest_querier, "getBranches");33 getBranches.mockReturnValue(Promise.resolve(branches));34 await actions.init(context, { repository_id: 42, project_id: 101 });35 expect(getBranches).toHaveBeenCalledWith(42);36 expect(context.commit).toHaveBeenCalledWith("setSourceBranches", [37 { display_name: "master", repository_id: 42, project_id: 101, name: "master" },38 {39 display_name: "feature/branch",40 repository_id: 42,41 project_id: 101,42 name: "feature/branch",43 },44 ]);45 });46 it("loads branches of current repository and store them as destination branches if there is no parent repository", async () => {47 const branches = [{ name: "master" }, { name: "feature/branch" }];48 const getBranches = jest.spyOn(rest_querier, "getBranches");49 getBranches.mockReturnValue(Promise.resolve(branches));50 await actions.init(context, { repository_id: 42, project_id: 101 });51 expect(context.commit).toHaveBeenCalledWith("setDestinationBranches", [52 { display_name: "master", repository_id: 42, project_id: 101, name: "master" },53 {54 display_name: "feature/branch",55 repository_id: 42,56 project_id: 101,57 name: "feature/branch",58 },59 ]);60 });61 it("loads branches of parent repository and add them as destination branches", async () => {62 const branches = [{ name: "master" }, { name: "feature/branch" }];63 const parent_branches = [{ name: "master" }, { name: "dev" }];64 jest.spyOn(rest_querier, "getBranches").mockImplementation((id) => {65 if (id === 42) {66 return Promise.resolve(branches);67 }68 if (id === 66) {69 return Promise.resolve(parent_branches);70 }71 throw new Error("Unexpected ID: " + id);72 });73 await actions.init(context, {74 repository_id: 42,75 project_id: 101,76 parent_repository_id: 66,77 parent_project_id: 102,78 parent_repository_name: "ledepot",79 });80 expect(context.commit).toHaveBeenCalledWith("setDestinationBranches", [81 { display_name: "master", repository_id: 42, project_id: 101, name: "master" },82 {83 display_name: "feature/branch",84 repository_id: 42,85 project_id: 101,86 name: "feature/branch",87 },88 {89 display_name: "ledepot : master",90 repository_id: 66,91 project_id: 102,92 name: "master",93 },94 { display_name: "ledepot : dev", repository_id: 66, project_id: 102, name: "dev" },95 ]);96 });97 it("switch the error flag if REST API returns an error", async () => {98 jest.spyOn(rest_querier, "getBranches").mockReturnValue(Promise.reject(500));99 await actions.init(context, {100 repository_id: 42,101 project_id: 101,102 parent_repository_id: 66,103 parent_project_id: 102,104 parent_repository_name: "ledepot",105 });106 expect(context.commit).toHaveBeenCalledWith("setHasErrorWhileLoadingBranchesToTrue");107 });108 });109 describe("create", () => {110 const source_branch = {111 repository_id: 102,112 project_id: 42,113 name: "feature/branch",114 };115 const destination_branch = {116 repository_id: 101,117 project_id: 42,118 name: "master",119 };120 it("calls the rest api to create the pull request", async () => {121 const created_pullrequest = { id: 1 };122 const createPullrequest = jest.spyOn(rest_querier, "createPullrequest");123 createPullrequest.mockReturnValue(Promise.resolve(created_pullrequest));124 jest.spyOn(window_helper, "redirectTo").mockImplementation(() => {});125 await actions.create(context, { source_branch, destination_branch });126 expect(createPullrequest).toHaveBeenCalledWith(102, "feature/branch", 101, "master");127 });128 it("does a full page reload to redirect to the created pull request", async () => {129 const created_pullrequest = { id: 1 };130 const createPullrequest = jest.spyOn(rest_querier, "createPullrequest");131 createPullrequest.mockReturnValue(Promise.resolve(created_pullrequest));132 const redirectTo = jest.spyOn(window_helper, "redirectTo").mockImplementation(() => {});133 await actions.create(context, { source_branch, destination_branch });134 expect(redirectTo).toHaveBeenCalledWith(135 "/plugins/git/?action=pull-requests&repo_id=101&group_id=42#/pull-requests/1/overview"136 );137 });138 it("Logs an error if the creation failed", async () => {139 const createPullrequest = jest.spyOn(rest_querier, "createPullrequest");140 createPullrequest.mockReturnValue(141 Promise.reject({142 response: {143 json() {144 return Promise.resolve({145 error: {146 message: "You cannot create this pullrequest",147 },148 });149 },150 },151 })152 );153 await actions.create(context, { source_branch, destination_branch });154 expect(createPullrequest).toHaveBeenCalledWith(102, "feature/branch", 101, "master");155 expect(context.commit).toHaveBeenCalledWith(156 "setCreateErrorMessage",157 "You cannot create this pullrequest"158 );159 });160 });...
actions.spec.js
Source:actions.spec.js
1/*2 * Copyright (c) Enalean, 2018. All Rights Reserved.3 *4 * This file is a part of Tuleap.5 *6 * Tuleap is free software; you can redistribute it and/or modify7 * it under the terms of the GNU General Public License as published by8 * the Free Software Foundation; either version 2 of the License, or9 * (at your option) any later version.10 *11 * Tuleap is distributed in the hope that it will be useful,12 * but WITHOUT ANY WARRANTY; without even the implied warranty of13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the14 * GNU General Public License for more details.15 *16 * You should have received a copy of the GNU General Public License17 * along with Tuleap. If not, see <http://www.gnu.org/licenses/>.18 */19import * as actions from "./actions.js";20import {21 restore as restoreRestQuerier,22 rewire$getBranches,23 rewire$createPullrequest24} from "../api/rest-querier.js";25import { restore as restoreWindow, rewire$redirectTo } from "../helpers/window-helper.js";26describe("Store actions", () => {27 let getBranches, createPullrequest, redirectTo, context;28 beforeEach(() => {29 context = {30 commit: jasmine.createSpy("commit")31 };32 getBranches = jasmine.createSpy("getBranches");33 rewire$getBranches(getBranches);34 createPullrequest = jasmine.createSpy("createPullrequest");35 rewire$createPullrequest(createPullrequest);36 redirectTo = jasmine.createSpy("redirectTo");37 rewire$redirectTo(redirectTo);38 });39 afterEach(() => {40 restoreRestQuerier();41 restoreWindow();42 });43 describe("init", () => {44 it("loads branches of current repository and store them as source branches", async () => {45 const branches = [{ name: "master" }, { name: "feature/branch" }];46 getBranches.withArgs(42).and.returnValue(Promise.resolve(branches));47 await actions.init(context, { repository_id: 42, project_id: 101 });48 expect(getBranches).toHaveBeenCalledWith(42);49 expect(context.commit).toHaveBeenCalledWith("setSourceBranches", [50 { display_name: "master", repository_id: 42, project_id: 101, name: "master" },51 {52 display_name: "feature/branch",53 repository_id: 42,54 project_id: 101,55 name: "feature/branch"56 }57 ]);58 });59 it("loads branches of current repository and store them as destination branches if there is no parent repository", async () => {60 const branches = [{ name: "master" }, { name: "feature/branch" }];61 getBranches.withArgs(42).and.returnValue(Promise.resolve(branches));62 await actions.init(context, { repository_id: 42, project_id: 101 });63 expect(context.commit).toHaveBeenCalledWith("setDestinationBranches", [64 { display_name: "master", repository_id: 42, project_id: 101, name: "master" },65 {66 display_name: "feature/branch",67 repository_id: 42,68 project_id: 101,69 name: "feature/branch"70 }71 ]);72 });73 it("loads branches of parent repository and add them as destination branches", async () => {74 const branches = [{ name: "master" }, { name: "feature/branch" }];75 const parent_branches = [{ name: "master" }, { name: "dev" }];76 getBranches.withArgs(42).and.returnValue(Promise.resolve(branches));77 getBranches.withArgs(66).and.returnValue(Promise.resolve(parent_branches));78 await actions.init(context, {79 repository_id: 42,80 project_id: 101,81 parent_repository_id: 66,82 parent_project_id: 102,83 parent_repository_name: "ledepot"84 });85 expect(context.commit).toHaveBeenCalledWith("setDestinationBranches", [86 { display_name: "master", repository_id: 42, project_id: 101, name: "master" },87 {88 display_name: "feature/branch",89 repository_id: 42,90 project_id: 101,91 name: "feature/branch"92 },93 {94 display_name: "ledepot : master",95 repository_id: 66,96 project_id: 102,97 name: "master"98 },99 { display_name: "ledepot : dev", repository_id: 66, project_id: 102, name: "dev" }100 ]);101 });102 it("switch the error flag if REST API returns an error", async () => {103 getBranches.and.returnValue(Promise.reject(500));104 await actions.init(context, {105 repository_id: 42,106 project_id: 101,107 parent_repository_id: 66,108 parent_project_id: 102,109 parent_repository_name: "ledepot"110 });111 expect(context.commit).toHaveBeenCalledWith("setHasErrorWhileLoadingBranchesToTrue");112 });113 });114 describe("create", () => {115 const source_branch = {116 repository_id: 102,117 project_id: 42,118 name: "feature/branch"119 };120 const destination_branch = {121 repository_id: 101,122 project_id: 42,123 name: "master"124 };125 it("calls the rest api to create the pull request", async () => {126 const created_pullrequest = { id: 1 };127 createPullrequest.and.returnValue(Promise.resolve(created_pullrequest));128 await actions.create(context, { source_branch, destination_branch });129 expect(createPullrequest).toHaveBeenCalledWith(102, "feature/branch", 101, "master");130 });131 it("it does a full page reload to redirect to the created pull request", async () => {132 const created_pullrequest = { id: 1 };133 createPullrequest.and.returnValue(Promise.resolve(created_pullrequest));134 await actions.create(context, { source_branch, destination_branch });135 expect(redirectTo).toHaveBeenCalledWith(136 "/plugins/git/?action=pull-requests&repo_id=101&group_id=42#/pull-requests/1/overview"137 );138 });139 it("Logs an error if the creation failed", async () => {140 createPullrequest.and.returnValue(141 Promise.reject({142 response: {143 json() {144 return Promise.resolve({145 error: {146 message: "You cannot create this pullrequest"147 }148 });149 }150 }151 })152 );153 await actions.create(context, { source_branch, destination_branch });154 expect(createPullrequest).toHaveBeenCalledWith(102, "feature/branch", 101, "master");155 expect(context.commit).toHaveBeenCalledWith(156 "setCreateErrorMessage",157 "You cannot create this pullrequest"158 );159 });160 });...
PullRequestController.js
Source:PullRequestController.js
1const apis = require('../apis/api');2const api = apis.requestGithubClient();3const diffUtils = require('../utils/diff/index');4var mongoose = require('mongoose')5const { ObjectId } = mongoose.Types;6const Sentry = require("@sentry/node");7const Repository = require('../models/Repository');8const PullRequest = require('../models/PullRequest');9const { checkValid } = require('../utils/utils');10const { pull } = require('lodash');11const createPullRequest = async (req, res) => {12 const {installationId, repositoryFullName, prData} = req.body;13 if (!checkValid(installationId)) return res.json({success: false, error: 'createPullRequest: No installationId provided'});14 if (!checkValid(repositoryFullName)) return res.json({success: false, error: 'createPullRequest: No repositoryFullName provided'});15 if (!checkValid(prData)) return res.json({success: false, error: 'createPullRequest: No prData provided'});16 17 // Get Repository Id18 var repositoryObj;19 try {20 repositoryObj = await Repository.findOne({ fullName: repositoryFullName }, '_id').lean().exec();21 }22 catch (err) {23 Sentry.setContext("createPullRequest", {24 message: `Repository findOne failed`,25 repositoryFullName: rrepositoryFullName,26 });27 Sentry.captureException(err);28 return res.json({success: false, error: `Repository findOne failed - repositoryFullName: ${repositoryFullName}`});29 }30 if (!repositoryObj) return res.json({success: false, error: `Repository findOne failed - repositoryFullName: ${repositoryFullName}`});31 if (!repositoryObj._id) return res.json({success: false, error: `Repository findOne failed - repositoryFullName: ${repositoryFullName}`});32 prData.installationId = installationId;33 prData.repository = repositoryObj._id.toString();34 console.log(`Creating PullRequest on Repository: ${prData.repository}`);35 let pullRequest = new PullRequest(prData);36 try {37 pullRequest = await pullRequest.save();38 }39 catch(err) {40 console.log(err);41 return res.json({success: false, error: err});42 }43 console.log("Successfully created Pull Request from Webhook Event");44 // Generate InsertHunk for PR Here45 // Pseudocode:46 // installationClient = await apis.requestInstallationClient(installationId);47 // prPatchContent = diffUtils.getPRDiffContent(installationClient, repositoryFullName, pullRequest.number);48 // insertHunks = diffUtils.createBlamesFromPRPatch(prPatchContent, pullRequest.number, pullRequest.repository);49 // diffUtils.createInsertHunks(insertHunks);50 // Get Installation Client51 var installationClient;52 try {53 installationClient = await apis.requestInstallationClient(installationId);54 }55 catch (err) {56 Sentry.setContext("createPullRequest", {57 message: `requestInstallationClient failed`,58 installationId: installationId,59 });60 Sentry.captureException(err);61 return res.json({success: false, error: `requestInstallationClient failed - installationId: ${installationId}`});62 }63 // Get Raw PR Patch Content64 var prPatchContent;65 try {66 prPatchContent = await diffUtils.getPRDiffContent(installationClient, repositoryFullName, pullRequest.number);67 }68 catch (err) {69 Sentry.setContext("createPullRequest", {70 message: `getPRDiffContent failed`,71 installationId: installationId,72 repositoryFullName: repositoryFullName,73 pullRequestNumber: pullRequest.number,74 });75 Sentry.captureException(err);76 return res.json({success: false,77 error: `getPRDiffContent failed - installationId, repositoryFullName, pullRequestNumber: ${installationId}, ${repositoryFullName}, ${pullRequestNumber}`78 });79 }80 // console.log("PR PATCH CONTENT: ");81 // console.log(prPatchContent);82 // Generate InsertHunks from raw patch content83 var insertHunks;84 try {85 insertHunks = diffUtils.createBlamesFromPRPatch(prPatchContent, pullRequest.number, pullRequest.repository);86 }87 catch (err) {88 Sentry.setContext("createPullRequest", {89 message: `createBlamesFromPRPatch failed`,90 pullRequestNumber: pullRequest.number,91 repositoryId: pullRequest.repository,92 });93 Sentry.captureException(err);94 return res.json({success: false, 95 error: `createBlamesFromPRPatch failed - repositoryId, pullRequestNumber: ${pullRequest.repository}, ${pullRequest.number}`96 });97 }98 // Save InsertHunks to DB99 if (insertHunks.length > 0) {100 try {101 diffUtils.createInsertHunks(insertHunks);102 }103 catch (err) {104 Sentry.setContext("createPullRequest", {105 message: `createInsertHunks failed`,106 numInsertHunks: insertHunks.length,107 repositoryId: pullRequest.repository,108 });109 110 Sentry.captureException(err);111 112 return res.json({success: false, 113 error: `createBlamesFromPRPatch failed - repositoryId, numInsertHunks: ${pullRequest.repository}, ${insertHunks.length}`114 });115 }116 }117 console.log(`Successfully Created ${insertHunks.length} InsertHunks for Repository ${prData.repository} `);118 return res.json({success: true, result: pullRequest});119}120module.exports = {121 createPullRequest...
test.js
Source:test.js
...63 t.plan(2);64 sandbox.stub(release, 'getMetadata').returns({ repoName });65 await release.initialiseGithubClient();66 sandbox.stub(githubInstance, 'createReleasePR');67 await release.createPullRequest();68 t.equal(githubInstance.createReleasePR.callCount, 1, 'Release pull request has been created');69 t.deepEqual(70 githubInstance.createReleasePR.getCall(0).args,71 [72 `${branchPrefix}-${version}`,73 releaseBranch,74 version,75 lastVersion,76 'extension'77 ],78 'Release pull request has been created from releasing branch',79 );80 sandbox.restore();81 t.end();82});83test('should log info message', async (t) => {84 t.plan(2);85 const url = 'testUrl';86 sandbox.stub(release, 'getMetadata').returns({ repoName });87 await release.initialiseGithubClient();88 sandbox.stub(githubInstance, 'createReleasePR').returns({89 state: 'open',90 html_url: url,91 });92 sandbox.stub(log, 'info');93 await release.createPullRequest();94 t.equal(log.info.callCount, 1, 'Info has been logged');95 t.ok(log.info.calledWith(`${url} created`), 'Info has been logged with appropriate message');96 sandbox.restore();97 t.end();98});99test('should set data.pr', async (t) => {100 t.plan(1);101 const html_url = 'testUrl';102 const apiUrl = 'apiUrl';103 const number = 42;104 const id = 'pr_id';105 const expectedPR = {106 url: html_url,107 apiUrl,108 number,109 id110 };111 sandbox.stub(release, 'getMetadata').returns({ repoName });112 await release.initialiseGithubClient();113 sandbox.stub(githubInstance, 'createReleasePR').returns({114 state: 'open',115 html_url,116 url: apiUrl,117 number,118 id119 });120 sandbox.stub(log, 'info');121 await release.createPullRequest();122 t.deepEqual(release.getData().pr, expectedPR, 'The PR data has been saved');123 sandbox.restore();124 t.end();125});126test('should log done message', async (t) => {127 t.plan(1);128 sandbox.stub(release, 'getMetadata').returns({ repoName });129 await release.initialiseGithubClient();130 sandbox.stub(githubInstance, 'createReleasePR').returns({131 state: 'open',132 });133 sandbox.stub(log, 'done');134 await release.createPullRequest();135 t.equal(log.done.callCount, 1, 'Done has been logged');136 sandbox.restore();137 t.end();138});139test('should log exit message if pull request is not created', async (t) => {140 t.plan(2);141 sandbox.stub(release, 'getMetadata').returns({ repoName });142 await release.initialiseGithubClient();143 sandbox.stub(log, 'exit');144 await release.createPullRequest();145 t.equal(log.exit.callCount, 1, 'Exit has been logged');146 t.ok(log.exit.calledWith('Unable to create the release pull request'), 'Exit has been logged with appropriate message');147 sandbox.restore();148 t.end();...
createPullRequest.spec.js
Source:createPullRequest.spec.js
...36 url: 'https://github.com/my/repo',37 }));38 });39 it('works in dry mode', async () => {40 const ret = await createPullRequest(getDefaultParams({ dryRun: true }));41 expect(run.mock.calls[0][0]).toMatchInlineSnapshot(`42 Object {43 "command": "git remote prune origin",44 "dir": ".",45 "dryRun": true,46 }47 `);48 expect(Octokit).toHaveBeenCalledTimes(0);49 expect(ret).toEqual({});50 });51 it('returns pr url', async () => {52 const create = jest.fn().mockImplementationOnce(() => ({53 data: { number: 13, html_url: 'https://github.com/my/repo/pull/13' }, // eslint-disable-line camelcase54 }));55 Octokit.mockImplementationOnce(function () {56 this.pulls = { create, requestReviewers: jest.fn() };57 });58 const { pullRequestUrl } = await createPullRequest(getDefaultParams());59 expect(pullRequestUrl).toEqual('https://github.com/my/repo/pull/13');60 });61 it('pass releaseType to hooks', () => {62 const mockFormatPullRequestTitle = jest63 .fn()64 .mockImplementation(({ version, type }) => `# v${version} (${type})`);65 const mockFormatPullRequestMessage = jest66 .fn()67 .mockImplementation(68 ({ formatPullRequestTitle, nextVersion, releaseType }) => {69 return [70 formatPullRequestTitle({71 version: nextVersion,72 releaseType,73 }),74 ].join('\n');75 }76 );77 createPullRequest(78 getDefaultParams({79 dryRun: true,80 formatPullRequestTitle: mockFormatPullRequestTitle,81 formatPullRequestMessage: mockFormatPullRequestMessage,82 })83 );84 expect(mockFormatPullRequestTitle).toHaveBeenCalledWith({85 version: '1.2.3',86 releaseType: 'patch',87 });88 expect(mockFormatPullRequestMessage).toHaveBeenCalled();89 expect(mockFormatPullRequestMessage.mock.calls[0][0]).toMatchObject({90 currentVersion: '1.2.2',91 nextVersion: '1.2.3',...
pullrequests.js
Source:pullrequests.js
...16- return: `Promise`17### Description18`createPullRequest` creates a PR19*/20function createPullRequest({title, body, head, base, owner, repository}) {21 return this.postData({path:`/repos/${owner}/${repository}/pulls`, data:{22 title, body, head, base23 }}).then(response => {24 return response.data;25 });26}27module.exports = {28 createPullRequest: createPullRequest...
Using AI Code Generation
1const github = require('cypress-github-api');2const pullRequest = github.createPullRequest({3});4module.exports = (on, config) => {5 on('task', {6 });7};8const github = require('cypress-github-api');9const release = github.createRelease({10});11module.exports = (on, config) => {12 on('task', {13 });14};15const github = require('cypress-github-api');16const status = github.createStatus({17});18module.exports = (on, config) => {19 on('task', {20 });21};22const github = require('cypress-github-api');23const branch = github.deleteBranch({24});25module.exports = (on, config) => {26 on('task', {27 });28};29const github = require('cypress-github-api');30const commitComment = github.deleteCommitComment({31});
Using AI Code Generation
1const github = require('cypress-github-api')2github.createPullRequest({3})4github.createPullRequest({5})6github.createIssue({7})8github.createComment({9})10github.updateComment({11})12github.deleteComment({13})14github.getIssueComments({15})16github.getPullRequestComments({
Using AI Code Generation
1const cypress = require('@cypress/github-api');2const { createPullRequest } = cypress.github;3createPullRequest({4}).then((response) => {5 console.log(response);6});7{8 data: {
Using AI Code Generation
1const createPullRequest = require('cypress-github-api/createPullRequest')2const response = createPullRequest(repoName,baseBranch,headBranch,title,body)3console.log(response)4const createPullRequestReviewComment = require('cypress-github-api/createPullRequestReviewComment')5const response = createPullRequestReviewComment(repoName,pullNumber,position,comment)6console.log(response)7const createPullRequestReview = require('cypress-github-api/createPullRequestReview')8const response = createPullRequestReview(repoName,pullNumber,commitId,event)9console.log(response)10const createPullRequestReviewThread = require('cypress-github-api/createPullRequestReviewThread')11const response = createPullRequestReviewThread(repoName,pullNumber,position,comment)12console.log(response)
Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.
You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!