Best JavaScript code snippet using cypress
deploy-web.test.js
Source:deploy-web.test.js
1/*2Copyright 2020 Adobe. All rights reserved.3This file is licensed to you under the Apache License, Version 2.0 (the "License");4you may not use this file except in compliance with the License. You may obtain a copy5of the License at http://www.apache.org/licenses/LICENSE-2.06Unless required by applicable law or agreed to in writing, software distributed under7the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS8OF ANY KIND, either express or implied. See the License for the specific language9governing permissions and limitations under the License.10*/11const { vol } = global.mockFs()12const deployWeb = require('../../src/deploy-web')13const fs = require('fs-extra')14jest.mock('fs-extra')15jest.mock('../../lib/getS3Creds')16const getS3Credentials = require('../../lib/getS3Creds')17getS3Credentials.mockResolvedValue('fakecreds')18const mockRemoteStorageInstance = {19 emptyFolder: jest.fn(),20 folderExists: jest.fn(),21 uploadDir: jest.fn()22}23const RemoteStorage = require('../../lib/remote-storage')24jest.mock('../../lib/remote-storage', () => {25 return jest.fn().mockImplementation(() => {26 return mockRemoteStorageInstance27 })28})29describe('deploy-web', () => {30 beforeEach(() => {31 RemoteStorage.mockClear()32 mockRemoteStorageInstance.emptyFolder.mockReset()33 mockRemoteStorageInstance.folderExists.mockReset()34 mockRemoteStorageInstance.uploadDir.mockReset()35 getS3Credentials.mockClear()36 global.cleanFs(vol)37 })38 test('throws if config does not have an app, or frontEnd', async () => {39 await expect(deployWeb()).rejects.toThrow('cannot deploy web')40 await expect(deployWeb({ app: 'nothing-here' })).rejects.toThrow('cannot deploy web')41 await expect(deployWeb({ app: { hasFrontEnd: false } })).rejects.toThrow('cannot deploy web')42 })43 test('throws if src dir does not exist', async () => {44 const config = {45 s3: {46 creds: 'not-null'47 },48 app: {49 hasFrontend: true50 },51 web: {52 distProd: 'dist'53 }54 }55 await expect(deployWeb(config)).rejects.toThrow('missing files in dist')56 })57 test('throws if src dir is not a directory', async () => {58 const config = {59 s3: {60 creds: 'not-null'61 },62 app: {63 hasFrontend: true64 },65 web: {66 distProd: 'dist'67 }68 }69 fs.existsSync.mockReturnValue(true)70 fs.lstatSync.mockReturnValue({ isDirectory: () => false })71 await expect(deployWeb(config)).rejects.toThrow('missing files in dist')72 })73 test('throws if src dir is empty', async () => {74 const config = {75 s3: {76 creds: 'not-null'77 },78 app: {79 hasFrontend: true80 },81 web: {82 distProd: 'dist'83 }84 }85 fs.existsSync.mockReturnValue(true)86 fs.lstatSync.mockReturnValue({ isDirectory: () => true })87 fs.readdirSync.mockReturnValue({ length: 0 })88 await expect(deployWeb(config)).rejects.toThrow('missing files in dist')89 })90 test('uploads files', async () => {91 const config = {92 ow: {93 namespace: 'ns',94 auth: 'password'95 },96 s3: {97 credsCacheFile: 'file',98 tvmUrl: 'url',99 folder: 'somefolder'100 },101 app: {102 hasFrontend: true,103 hostname: 'host'104 },105 web: {106 distProd: 'dist'107 }108 }109 fs.existsSync.mockReturnValue(true)110 fs.lstatSync.mockReturnValue({ isDirectory: () => true })111 fs.readdirSync.mockReturnValue({ length: 1 })112 await expect(deployWeb(config)).resolves.toEqual('https://ns.host/index.html')113 expect(getS3Credentials).toHaveBeenCalledWith(config)114 expect(RemoteStorage).toHaveBeenCalledWith('fakecreds')115 expect(mockRemoteStorageInstance.uploadDir).toHaveBeenCalledWith('dist', 'somefolder', config.app, null)116 expect(mockRemoteStorageInstance.emptyFolder).not.toHaveBeenCalled()117 expect(mockRemoteStorageInstance.folderExists).toHaveBeenCalledWith('somefolder/')118 })119 test('uploads files with log func', async () => {120 const config = {121 ow: {122 namespace: 'ns',123 auth: 'password'124 },125 s3: {126 credsCacheFile: 'file',127 tvmUrl: 'url',128 folder: 'somefolder'129 },130 app: {131 hasFrontend: true,132 hostname: 'host'133 },134 web: {135 distProd: 'dist'136 }137 }138 fs.existsSync.mockReturnValue(true)139 fs.lstatSync.mockReturnValue({ isDirectory: () => true })140 fs.readdirSync.mockReturnValue({ length: 1 })141 const mockLogger = jest.fn()142 // for func coverage143 mockRemoteStorageInstance.uploadDir.mockImplementation((a, b, c, func) => func('somefile'))144 await expect(deployWeb(config, mockLogger)).resolves.toEqual('https://ns.host/index.html')145 expect(getS3Credentials).toHaveBeenCalledWith(config)146 expect(RemoteStorage).toHaveBeenCalledWith('fakecreds')147 expect(mockRemoteStorageInstance.uploadDir).toHaveBeenCalledWith('dist', 'somefolder', config.app, expect.any(Function))148 expect(mockRemoteStorageInstance.emptyFolder).not.toHaveBeenCalled()149 expect(mockRemoteStorageInstance.folderExists).toHaveBeenCalledWith('somefolder/')150 })151 test('overwrites remote files', async () => {152 const config = {153 ow: {154 namespace: 'ns',155 auth: 'password'156 },157 s3: {158 creds: 'somecreds',159 folder: 'somefolder'160 },161 app: {162 hasFrontend: true,163 hostname: 'host'164 },165 web: {166 distProd: 'dist'167 }168 }169 fs.existsSync.mockReturnValue(true)170 fs.lstatSync.mockReturnValue({ isDirectory: () => true })171 const mockLogger = jest.fn()172 fs.readdirSync.mockReturnValue({ length: 1 })173 mockRemoteStorageInstance.folderExists.mockResolvedValue(true)174 await expect(deployWeb(config, mockLogger)).resolves.toEqual('https://ns.host/index.html')175 expect(getS3Credentials).toHaveBeenCalledWith(config)176 expect(mockLogger).toHaveBeenCalledWith('warning: an existing deployment will be overwritten')177 expect(RemoteStorage).toHaveBeenCalledWith('fakecreds')178 expect(mockRemoteStorageInstance.folderExists).toHaveBeenCalledWith('somefolder/')179 expect(mockRemoteStorageInstance.uploadDir).toHaveBeenCalledWith('dist', 'somefolder', config.app, expect.any(Function))180 // empty dir!181 expect(mockRemoteStorageInstance.emptyFolder).toHaveBeenCalledWith('somefolder/')182 })183 test('overwrites remote files no log func', async () => {184 const config = {185 ow: {186 namespace: 'ns',187 auth: 'password'188 },189 s3: {190 folder: 'somefolder'191 },192 app: {193 hasFrontend: true,194 hostname: 'host'195 },196 web: {197 distProd: 'dist'198 }199 }200 fs.existsSync.mockReturnValue(true)201 fs.lstatSync.mockReturnValue({ isDirectory: () => true })202 fs.readdirSync.mockReturnValue({ length: 1 })203 mockRemoteStorageInstance.folderExists.mockResolvedValue(true)204 await expect(deployWeb(config)).resolves.toEqual('https://ns.host/index.html')205 expect(getS3Credentials).toHaveBeenCalledWith(config)206 expect(mockRemoteStorageInstance.folderExists).toHaveBeenCalledWith('somefolder/')207 expect(mockRemoteStorageInstance.uploadDir).toHaveBeenCalledWith('dist', 'somefolder', config.app, null)208 // empty dir!209 expect(mockRemoteStorageInstance.emptyFolder).toHaveBeenCalledWith('somefolder/')210 })211 test('calls to s3 should use ending slash', async () => {212 const config = {213 ow: {214 namespace: 'ns',215 auth: 'password'216 },217 s3: {218 credsCacheFile: 'file',219 tvmUrl: 'url',220 folder: 'nsfolder'221 },222 app: {223 hasFrontend: true,224 hostname: 'host'225 },226 web: {227 distProd: 'dist'228 }229 }230 const emptyFolder = jest.fn()231 const folderExists = jest.fn(() => true)232 RemoteStorage.mockImplementation(() => {233 return {234 emptyFolder,235 folderExists,236 uploadDir: jest.fn()237 }238 })239 fs.existsSync.mockReturnValue(true)240 fs.lstatSync.mockReturnValue({ isDirectory: () => true })241 const mockLogger = jest.fn()242 fs.readdirSync.mockReturnValue({ length: 1 })243 await expect(deployWeb(config, mockLogger)).resolves.toEqual('https://ns.host/index.html')244 expect(getS3Credentials).toHaveBeenCalled()245 expect(RemoteStorage).toHaveBeenCalledTimes(1)246 expect(folderExists).toHaveBeenLastCalledWith('nsfolder/')247 expect(emptyFolder).toHaveBeenLastCalledWith('nsfolder/')248 })...
S3KeyService.js
Source:S3KeyService.js
...5 * Find s3 temporary credentials using STS method6 * @param {Object} reqObj - Request object7 * @param {Object} serviceCallback - service callback8 */9async function getS3Credentials(reqObj, serviceCallback) {10 const sts = new AWS.STS({ region: 'us-west-2' });11 S3KeyService.getEC2Rolename(AWS).then((rolename) => {12 let s3Params = {13 RoleArn: arnName + rolename,14 RoleSessionName: 'DEV_SESSION_S3',15 ExternalId: Math.floor((Math.random() * 10000000000000)).toString() + '',16 DurationSeconds: 900,17 };18 sts.assumeRole(s3Params, (err, data) => {19 if (err) {20 console.log("assumeRole error: ", err);21 serviceCallback({ status: false, result: [] });22 } else {23 let s3Object = { AccessKeyId: data.Credentials.AccessKeyId, secretAccessKey: data.Credentials.SecretAccessKey, sessionToken: data.Credentials.SessionToken };24 serviceCallback({ status: true, result: s3Object });25 }26 });27 }).catch((err) => {28 console.log(err);29 serviceCallback({ status: false, result: [] });30 });31}32/**33 * Get EC2 Rolename against the current user34 * @param {AWS} AWS - Aws service35 * @returns {Object} - Promise object36 */37async function getEC2Rolename(AWS) {38 let promise = new Promise((resolve, reject) => {39 let metadata = new AWS.MetadataService();40 metadata.request('/latest/meta-data/iam/security-credentials/', (err, rolename) => {41 if (err) { reject(err); }42 resolve(rolename);43 });44 });45 return promise;46}47async function uploadSdsFile(req, res) {48 try {49 let fileName = "SOPTemplateTest" + "_" + Math.floor((Math.random() * 10000000000000) + 1) + '.html';50 let content = "This is for the test purpose";51 let s3Name = 'sdstemplates/' + fileName;52 console.log("logger 1");53 S3KeyService.getS3Credentials(req, function (s3KeyResponse) {54 console.log("s3KeyResponse", s3KeyResponse);55 if (s3KeyResponse.status) {56 let s3client = new AWS.S3({57 accessKeyId: s3KeyResponse.result.AccessKeyId,58 secretAccessKey: s3KeyResponse.result.secretAccessKey,59 sessionToken: s3KeyResponse.result.sessionToken,60 params: {61 Bucket: 'albert-assets',62 Key: s3Name63 }64 });65 s3client.upload({ ACL: 'private', Body: content, 'ContentType': 'text/html', 'ContentDisposition': 'inline' }, function (err, result) {66 if (err) {67 console.log("error 1: ", err);...
undeploy-web.test.js
Source:undeploy-web.test.js
1/*2Copyright 2020 Adobe. All rights reserved.3This file is licensed to you under the Apache License, Version 2.0 (the "License");4you may not use this file except in compliance with the License. You may obtain a copy5of the License at http://www.apache.org/licenses/LICENSE-2.06Unless required by applicable law or agreed to in writing, software distributed under7the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS8OF ANY KIND, either express or implied. See the License for the specific language9governing permissions and limitations under the License.10*/11const undeployWeb = require('../../src/undeploy-web')12jest.mock('../../lib/getS3Creds')13const getS3Credentials = require('../../lib/getS3Creds')14getS3Credentials.mockResolvedValue('fakecreds')15const mockRemoteStorageInstance = {16 emptyFolder: jest.fn(),17 folderExists: jest.fn()18}19const RemoteStorage = require('../../lib/remote-storage')20jest.mock('../../lib/remote-storage', () => {21 return jest.fn().mockImplementation(() => {22 return mockRemoteStorageInstance23 })24})25describe('undeploy-web', () => {26 beforeEach(() => {27 RemoteStorage.mockClear()28 mockRemoteStorageInstance.emptyFolder.mockReset()29 mockRemoteStorageInstance.folderExists.mockReset()30 getS3Credentials.mockClear()31 })32 test('throws if config does not have an app, or frontEnd', async () => {33 await expect(undeployWeb()).rejects.toThrow('cannot undeploy web')34 await expect(undeployWeb({ app: 'nothing-here' })).rejects.toThrow('cannot undeploy web')35 await expect(undeployWeb({ app: { hasFrontEnd: false } })).rejects.toThrow('cannot undeploy web')36 })37 test('calls getS3Credentials and empties folder', async () => {38 const config = {39 ow: {40 namespace: 'ns',41 auth: 'password'42 },43 s3: {44 creds: 'fakes3creds',45 tvmUrl: 'url',46 folder: 'somefolder'47 },48 app: {49 hasFrontend: true,50 hostname: 'host'51 },52 web: {53 distProd: 'dist'54 }55 }56 mockRemoteStorageInstance.folderExists.mockResolvedValue(true)57 await undeployWeb(config)58 expect(getS3Credentials).toHaveBeenCalledWith(config)59 expect(RemoteStorage).toHaveBeenCalledWith('fakecreds')60 expect(mockRemoteStorageInstance.folderExists).toHaveBeenCalledWith('somefolder')61 expect(mockRemoteStorageInstance.emptyFolder).toHaveBeenCalledWith('somefolder')62 })63 test('throws if remoteStorage folder does not exist', async () => {64 const config = {65 ow: {66 namespace: 'ns',67 auth: 'password'68 },69 s3: {70 credsCacheFile: 'file',71 tvmUrl: 'url',72 folder: 'somefolder'73 },74 app: {75 hasFrontend: true76 },77 web: {78 distProd: 'dist'79 }80 }81 await expect(undeployWeb(config)).rejects.toThrow('cannot undeploy static files')82 expect(getS3Credentials).toHaveBeenCalledWith(config)83 expect(RemoteStorage).toHaveBeenCalledWith('fakecreds')84 expect(mockRemoteStorageInstance.folderExists).toHaveBeenCalledWith('somefolder')85 expect(mockRemoteStorageInstance.emptyFolder).not.toHaveBeenCalled()86 })...
signatureGenerator.js
Source:signatureGenerator.js
1var config = require('./config');2var crypto = require('crypto');3function getS3Credentials(config, filename) {4 var params = getS3Parameters(config, filename);5 var result = {6 upload_url: "https://" + config.bucket + ".s3.amazonaws.com",7 params: params8 };9 return result;10}11// Returns the parameters that need to be send with the AWS' upload API12function getS3Parameters(config, filename) {13 var date = new Date().toISOString();14 // create date string for the current date15 var dateString = date.substr(0, 4) + date.substr(5, 2) + date.substr(8, 2);16 // create upload credentials17 var credential = config.access_key + "/" + dateString + "/" + config.region + "/s3/aws4_request";...
getS3Creds.test.js
Source:getS3Creds.test.js
...17 })18 test('throw when missing required args', async () => {19 const expectedErrorMessage =20 'Please check your .env file to ensure your credentials are correct.'21 await expect(getS3Credentials({}))22 .rejects.toThrow(expectedErrorMessage)23 await expect(getS3Credentials({ ow: { namespace: 'ns' }, s3: {} }))24 .rejects.toThrow(expectedErrorMessage)25 await expect(getS3Credentials({ ow: { auth: 'auth' } }))26 .rejects.toThrow(expectedErrorMessage)27 })28 test('returns s3.creds if defined', async () => {29 const fakeCreds = { fake: 's3creds' }30 await expect(getS3Credentials({ ow: { namespace: 'ns', auth: 'auth' }, s3: { creds: fakeCreds } }))31 .resolves.toEqual(fakeCreds)32 expect(mockTVM.init).not.toHaveBeenCalled()33 })34 test('gets credentials from tvm', async () => {35 await expect(getS3Credentials({ ow: { namespace: 'ns', auth: 'auth' } }))36 .resolves.toEqual(fakeReturnedTvmCreds)37 expect(mockTVM.init).toBeCalledWith({38 apiUrl: undefined,39 cacheFile: undefined,40 ow: { auth: 'auth', namespace: 'ns' }41 })42 })43 test('gets credentials from tvm with custom tvmurl', async () => {44 await expect(getS3Credentials({ ow: { namespace: 'ns', auth: 'auth' }, s3: { tvmUrl: 'custom' } }))45 .resolves.toEqual(fakeReturnedTvmCreds)46 expect(mockTVM.init).toBeCalledWith({47 apiUrl: 'custom',48 cacheFile: undefined,49 ow: { auth: 'auth', namespace: 'ns' }50 })51 })52 test('gets credentials from tvm with custom credsCacheFile', async () => {53 await expect(getS3Credentials({ ow: { namespace: 'ns', auth: 'auth' }, s3: { credsCacheFile: 'custom' } }))54 .resolves.toEqual(fakeReturnedTvmCreds)55 expect(mockTVM.init).toBeCalledWith({56 apiUrl: undefined,57 cacheFile: 'custom',58 ow: { auth: 'auth', namespace: 'ns' }59 })60 })...
amazon.js
Source:amazon.js
1var Config = require('../config/environment.js'),2 my_config = new Config();3var AWS = require('aws-sdk');4module.exports = function(){5 //form sts object from environment variables. Used for retrieving temporary credentials to front end6 var sts = new AWS.STS();7 //configure credentials for use on server only; assign credentials based on role (never use master credentials)8 AWS.config.credentials = new AWS.EnvironmentCredentials('AWS');9 AWS.config.credentials = new AWS.TemporaryCredentials({10 RoleArn: 'arn:aws:iam::578381890239:role/msdAdmin'11 });12 //s3 object for use on server13 var s3 = new AWS.S3();14 //bucket retrieved from environment variables15 var amazonBucket = my_config.amazonBucket;16 //================================================================================================= amazon s3 functions17 // Used for retrieving temporary credentials to front end18 var getS3Credentials = function(RoleSessionName, callback){19 sts.assumeRole({20 RoleArn: 'arn:aws:iam::578381890239:role/msdAdmin',21 RoleSessionName: RoleSessionName,22 DurationSeconds: 90023 }, function (err, data) {24 if(err){25 callback(err, null);26 }else{27 callback(null, data);28 }29 });30 };31 //function for deleting object from amazon32 var deleteObjectS3 = function (key, callback) {33 s3.deleteObject({Bucket: amazonBucket, Key: key}, function (err, data) {34 callback(err, data);35 });36 };37 var addObjectS3 = function(key,body,callback){38 if(typeof body === "string") body = new Buffer(body,'base64');39 s3.upload({Bucket: amazonBucket,Key: key, Body:body, ACL:'public-read'}, function (err, data2) {40 callback(err, data2);41 });42 };43 return {44 getS3Credentials: getS3Credentials,45 deleteObjectS3: deleteObjectS3,46 addObjectS3: addObjectS347 };...
credentialsFactory.factory.js
Source:credentialsFactory.factory.js
1"use strict";2app.factory("credentialsFactory", function($q, $http){3var getGetResponseCredentials = () => {4 return $q(function(resolve, reject){5 $http6 .get("data/getResponse.json")7 .success(function(credentials){8 resolve(credentials.credentials);9 })10 .error(function(error){11 reject(error);12 });13 });14 };15 var getS3Credentials = () => {16 return $q(function(resolve, reject){17 $http18 .get("data/S3.json")19 .success(function(credentials){20 resolve(credentials.credentials);21 })22 .error(function(error){23 reject(error);24 });25 });26 };27 return {getGetResponseCredentials: getGetResponseCredentials, getS3Credentials: getS3Credentials};...
index.js
Source:index.js
1import getS3Credentials from './getS3Credentials';...
Using AI Code Generation
1describe('S3 Upload', () => {2 it('Upload file to s3', () => {3 cy.getS3Credentials().then((response) => {4 const { accessKeyId, secretAccessKey, sessionToken, bucket, region } = response.body;5 const credentials = new AWS.Credentials({6 });7 const s3 = new AWS.S3({8 });9 const params = {10 };11 s3.upload(params, (err, data) => {12 if (err) {13 console.log(err);14 } else {15 console.log(data);16 }17 });18 });19 });20});
Using AI Code Generation
1describe('test', function() {2 it('test', function() {3 }).then((response) => {4 expect(response.status).to.eq(200)5 expect(response.body).to.have.property('accessKeyId')6 expect(response.body).to.have.property('secretAccessKey')7 expect(response.body).to.have.property('sessionToken')8 expect(response.body).to.have.property('expiration')9 expect(response.body).to.have.property('region')10 expect(response.body).to.have.property('bucket')11 })12 })13})14describe('test', function() {15 it('test', function() {16 }).then((response) => {17 expect(response.status).to.eq(200)18 expect(response.body).to.have.property('accessKeyId')19 expect(response.body).to.have.property('secretAccessKey')20 expect(response.body).to.have.property('sessionToken')21 expect(response.body).to.have.property('expiration')22 expect(response.body).to.have.property('region')23 expect(response.body).to.have.property('bucket')24 })25 })26})27describe('test', function() {28 it('test', function() {29 }).then((response) => {30 expect(response.status).to.eq(200)31 expect(response.body).to.have.property('accessKeyId')32 expect(response.body).to.have.property('secretAccessKey')33 expect(response.body).to.have.property('sessionToken')34 expect(response.body).to.have.property('expiration')35 expect(response.body).to.have.property('region')36 expect(response.body).to.have.property('bucket')37 })38 })39})40describe('test', function() {41 it('test', function() {42 cy.request('POST', '
Using AI Code Generation
1import {getS3Credentials} from 'cypress-aws-s3-upload';2describe('Upload to S3', () => {3 it('Upload file to S3', () => {4 getS3Credentials().then((credentials) => {5 cy.uploadFile(6 {7 httpUploadProgress: (progressEvent) => {8 console.log(9 `Upload is ${Math.round(10 (progressEvent.loaded / progressEvent.total) * 10011 )}% done`12 );13 },14 },15 {16 }17 );18 });19 });20});21Cypress.Commands.add('getS3Credentials', () => {22 return cy.request({23 });24});25Cypress.Commands.add('uploadFile', (fileName, credentials, options, s3Options) => {26 const {accessKeyId, secretAccessKey, sessionToken} = credentials;27 const {28 body: {url},29 } = credentials;30 const uploadOptions = {31 headers: {32 'x-amz-credential': `${accessKeyId}/${credentials.body.date}/${credentials.body.region}/s3/aws4_request`,33 },34 };35 const s3OptionsWithDefaults = {36 };37 return cy.fixture(fileName, 'base64').then((content) => {38 .request({
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!!