Best JavaScript code snippet using supertest
helpers.ts
Source:helpers.ts
1import { STATUS_CODES } from "http";2import { inspect } from "util";3import * as supertest from "supertest";4import { expect, AssertionError } from "chai";5import { IdpJwtPayload } from "../../../emulator/auth/operations";6import { OobRecord, PhoneVerificationRecord, UserInfo } from "../../../emulator/auth/state";7import { TestAgent, PROJECT_ID } from "./setup";8import { MfaEnrollments } from "../../../emulator/auth/types";9export { PROJECT_ID };10export const TEST_PHONE_NUMBER = "+15555550100";11export const TEST_PHONE_NUMBER_2 = "+15555550101";12export const TEST_PHONE_NUMBER_3 = "+15555550102";13export const TEST_MFA_INFO = {14 displayName: "Cell Phone",15 phoneInfo: TEST_PHONE_NUMBER,16};17export const TEST_INVALID_PHONE_NUMBER = "5555550100"; /* no country code */18export const FAKE_GOOGLE_ACCOUNT = {19 displayName: "Example User",20 email: "example@gmail.com",21 emailVerified: true,22 rawId: "123456789012345678901",23 // An unsigned token, with payload format similar to a real one.24 idToken:25 "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwiYXpwIjoiMjI4NzQ2ODI4NDQtYjBzOHM3NWIzaWVkYjJtZDRobHMydm9xNnNsbGJzbTMuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiIyMjg3NDY4Mjg0NC1iMHM4czc1YjNpZWRiMm1kNGhsczJ2b3E2c2xsYnNtMy5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsInN1YiI6IjEyMzQ1Njc4OTAxMjM0NTY3ODkwMSIsImVtYWlsIjoiZXhhbXBsZUBnbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiYXRfaGFzaCI6IjAwMDAwMDAwMDAwMDAwMDAwMDAwMDAiLCJpYXQiOjE1OTc4ODI2ODEsImV4cCI6MTU5Nzg4NjI4MX0.",26 // Same as above, except with no email included.27 idTokenNoEmail:28 "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwiYXpwIjoiMjI4NzQ2ODI4NDQtYjBzOHM3NWIzaWVkYjJtZDRobHMydm9xNnNsbGJzbTMuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiIyMjg3NDY4Mjg0NC1iMHM4czc1YjNpZWRiMm1kNGhsczJ2b3E2c2xsYnNtMy5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsInN1YiI6IjEyMzQ1Njc4OTAxMjM0NTY3ODkwMSIsImF0X2hhc2giOiIwMDAwMDAwMDAwMDAwMDAwMDAwMDAwIiwiaWF0IjoxNTk3ODgyNjgxLCJleHAiOjE1OTc4ODYyODF9.",29};30// This is a real Google test account (go/rhea), owned and managed by a Googler.31// However, nobody needs to actually sign-in using this account -- no tests32// below requires actual Google sign-in, and the Auth Emulator doesn't validate.33// If for some reason the account or idToken below doesn't fit our testing need34// anymore, create a new test account and token. Don't ping anyone for password.35export const REAL_GOOGLE_ACCOUNT = {36 displayName: "Oberyn Baelish",37 email: "oberynbaelish.331826@gmail.com",38 emailVerified: true,39 rawId: "115113236566683398301",40 photoUrl:41 "https://lh3.googleusercontent.com/-KNaMyFnKZ9o/AAAAAAAAAAI/AAAAAAAAAAA/AMZuucnZC9bn4HcT-8bQka3uG3lUYd4lSA/photo.jpg",42 // ID Tokens below are also real, but their signatures has been zero'd out and43 // have expired long ago, so they are safe to use as examples in tests below.44 idToken:45 "eyJhbGciOiJSUzI1NiIsImtpZCI6IjZiYzYzZTlmMThkNTYxYjM0ZjU2NjhmODhhZTI3ZDQ4ODc2ZDgwNzMiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwiYXpwIjoiMjI4NzQ2ODI4NDQtYjBzOHM3NWIzaWVkYjJtZDRobHMydm9xNnNsbGJzbTMuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiIyMjg3NDY4Mjg0NC1iMHM4czc1YjNpZWRiMm1kNGhsczJ2b3E2c2xsYnNtMy5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsInN1YiI6IjExNTExMzIzNjU2NjY4MzM5ODMwMSIsImVtYWlsIjoib2JlcnluYmFlbGlzaC4zMzE4MjZAZ21haWwuY29tIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImF0X2hhc2giOiJXNTlTOEs4Y3g0Y3hYYmh0YmFXYndBIiwiaWF0IjoxNTk3ODgyNjgxLCJleHAiOjE1OTc4ODYyODF9.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",46 idTokenNoEmail:47 "eyJhbGciOiJSUzI1NiIsImtpZCI6IjZiYzYzZTlmMThkNTYxYjM0ZjU2NjhmODhhZTI3ZDQ4ODc2ZDgwNzMiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwiYXpwIjoiMjI4NzQ2ODI4NDQtYjBzOHM3NWIzaWVkYjJtZDRobHMydm9xNnNsbGJzbTMuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiIyMjg3NDY4Mjg0NC1iMHM4czc1YjNpZWRiMm1kNGhsczJ2b3E2c2xsYnNtMy5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsInN1YiI6IjExNTExMzIzNjU2NjY4MzM5ODMwMSIsImF0X2hhc2giOiJJRHA0UFFldFItLUFyaWhXX2NYMmd3IiwiaWF0IjoxNTk3ODgyNDQyLCJleHAiOjE1OTc4ODYwNDJ9.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",48};49/**50 * Asserts that the response has the expected status code.51 * @param expected the expected status code52 * @param res the supertest Response53 */54export function expectStatusCode(expected: number, res: supertest.Response): void {55 if (res.status !== expected) {56 const body = inspect(res.body);57 throw new AssertionError(58 `expected ${expected} "${STATUS_CODES[expected]}", got ${res.status} "${59 STATUS_CODES[res.status]60 }", with response body:\n${body}`61 );62 }63}64/**65 * Create a fake claims object with some default field values plus custom ones.66 * @param input custom field values67 * @return a complete claims plain JS object68 */69export function fakeClaims(input: Partial<IdpJwtPayload> & { sub: string }): IdpJwtPayload {70 return Object.assign(71 {72 iss: "example.com",73 aud: "example.com",74 exp: 1597974008,75 iat: 1597970408,76 },77 input78 );79}80/* eslint-disable jsdoc/require-jsdoc */81// Most functions below are self-documenting test helpers.82export function registerUser(83 testAgent: TestAgent,84 user: {85 email: string;86 password: string;87 displayName?: string;88 mfaInfo?: MfaEnrollments;89 }90): Promise<{ idToken: string; localId: string; refreshToken: string; email: string }> {91 return testAgent92 .post("/identitytoolkit.googleapis.com/v1/accounts:signUp")93 .send(user)94 .query({ key: "fake-api-key" })95 .then((res) => {96 expectStatusCode(200, res);97 return {98 idToken: res.body.idToken,99 localId: res.body.localId,100 refreshToken: res.body.refreshToken,101 email: res.body.email,102 };103 });104}105export function registerAnonUser(106 testAgent: TestAgent107): Promise<{ idToken: string; localId: string; refreshToken: string }> {108 return testAgent109 .post("/identitytoolkit.googleapis.com/v1/accounts:signUp")110 .send({ returnSecureToken: true })111 .query({ key: "fake-api-key" })112 .then((res) => {113 expectStatusCode(200, res);114 return {115 idToken: res.body.idToken,116 localId: res.body.localId,117 refreshToken: res.body.refreshToken,118 };119 });120}121export async function signInWithEmailLink(122 testAgent: TestAgent,123 email: string,124 idTokenToLink?: string125): Promise<{ idToken: string; localId: string; refreshToken: string; email: string }> {126 const { oobCode } = await createEmailSignInOob(testAgent, email);127 return testAgent128 .post("/identitytoolkit.googleapis.com/v1/accounts:signInWithEmailLink")129 .query({ key: "fake-api-key" })130 .send({ email, oobCode, idToken: idTokenToLink })131 .then((res) => {132 return {133 idToken: res.body.idToken,134 localId: res.body.localId,135 refreshToken: res.body.refreshToken,136 email,137 };138 });139}140export function signInWithPassword(141 testAgent: TestAgent,142 email: string,143 password: string144): Promise<{ idToken: string; localId: string; refreshToken: string; email: string }> {145 return testAgent146 .post("/identitytoolkit.googleapis.com/v1/accounts:signInWithPassword")147 .send({ email, password })148 .query({ key: "fake-api-key" })149 .then((res) => {150 expectStatusCode(200, res);151 return {152 idToken: res.body.idToken,153 localId: res.body.localId,154 refreshToken: res.body.refreshToken,155 email: res.body.email,156 };157 });158}159export async function signInWithPhoneNumber(160 testAgent: TestAgent,161 phoneNumber: string162): Promise<{ idToken: string; localId: string; refreshToken: string }> {163 const sessionInfo = await testAgent164 .post("/identitytoolkit.googleapis.com/v1/accounts:sendVerificationCode")165 .query({ key: "fake-api-key" })166 .send({ phoneNumber, recaptchaToken: "ignored" })167 .then((res) => {168 expectStatusCode(200, res);169 return res.body.sessionInfo;170 });171 const codes = await inspectVerificationCodes(testAgent);172 return testAgent173 .post("/identitytoolkit.googleapis.com/v1/accounts:signInWithPhoneNumber")174 .query({ key: "fake-api-key" })175 .send({ sessionInfo, code: codes[0].code })176 .then((res) => {177 expectStatusCode(200, res);178 return {179 idToken: res.body.idToken,180 localId: res.body.localId,181 refreshToken: res.body.refreshToken,182 };183 });184}185export function signInWithFakeClaims(186 testAgent: TestAgent,187 providerId: string,188 claims: Partial<IdpJwtPayload> & { sub: string }189): Promise<{ idToken: string; localId: string; refreshToken: string; email?: string }> {190 const fakeIdToken = JSON.stringify(fakeClaims(claims));191 return testAgent192 .post("/identitytoolkit.googleapis.com/v1/accounts:signInWithIdp")193 .query({ key: "fake-api-key" })194 .send({195 postBody: `providerId=${encodeURIComponent(providerId)}&id_token=${encodeURIComponent(196 fakeIdToken197 )}`,198 requestUri: "http://localhost",199 returnIdpCredential: true,200 returnSecureToken: true,201 })202 .then((res) => {203 expectStatusCode(200, res);204 return {205 idToken: res.body.idToken,206 localId: res.body.localId,207 refreshToken: res.body.refreshToken,208 email: res.body.email,209 };210 });211}212export async function expectUserNotExistsForIdToken(213 testAgent: TestAgent,214 idToken: string215): Promise<void> {216 await testAgent217 .post("/identitytoolkit.googleapis.com/v1/accounts:lookup")218 .send({ idToken })219 .query({ key: "fake-api-key" })220 .then((res) => {221 expectStatusCode(400, res);222 expect(res.body.error).to.have.property("message").equals("USER_NOT_FOUND");223 });224}225export async function expectIdTokenExpired(testAgent: TestAgent, idToken: string): Promise<void> {226 await testAgent227 .post("/identitytoolkit.googleapis.com/v1/accounts:lookup")228 .send({ idToken })229 .query({ key: "fake-api-key" })230 .then((res) => {231 expectStatusCode(400, res);232 expect(res.body.error).to.have.property("message").equals("TOKEN_EXPIRED");233 });234}235export function getAccountInfoByIdToken(testAgent: TestAgent, idToken: string): Promise<UserInfo> {236 return testAgent237 .post("/identitytoolkit.googleapis.com/v1/accounts:lookup")238 .send({ idToken })239 .query({ key: "fake-api-key" })240 .then((res) => {241 expectStatusCode(200, res);242 expect(res.body.users || []).to.have.length(1);243 return res.body.users[0];244 });245}246export function getAccountInfoByLocalId(testAgent: TestAgent, localId: string): Promise<UserInfo> {247 return testAgent248 .post("/identitytoolkit.googleapis.com/v1/accounts:lookup")249 .send({ localId: [localId] })250 .set("Authorization", "Bearer owner")251 .then((res) => {252 expectStatusCode(200, res);253 expect(res.body.users || []).to.have.length(1);254 return res.body.users[0];255 });256}257export function inspectOobs(testAgent: TestAgent): Promise<OobRecord[]> {258 return testAgent.get(`/emulator/v1/projects/${PROJECT_ID}/oobCodes`).then((res) => {259 expectStatusCode(200, res);260 return res.body.oobCodes;261 });262}263export function inspectVerificationCodes(testAgent: TestAgent): Promise<PhoneVerificationRecord[]> {264 return testAgent.get(`/emulator/v1/projects/${PROJECT_ID}/verificationCodes`).then((res) => {265 expectStatusCode(200, res);266 return res.body.verificationCodes;267 });268}269export function createEmailSignInOob(270 testAgent: TestAgent,271 email: string272): Promise<{ oobCode: string; oobLink: string }> {273 return testAgent274 .post("/identitytoolkit.googleapis.com/v1/accounts:sendOobCode")275 .send({ email, requestType: "EMAIL_SIGNIN", returnOobLink: true })276 .set("Authorization", "Bearer owner")277 .then((res) => {278 expectStatusCode(200, res);279 return {280 oobCode: res.body.oobCode,281 oobLink: res.body.oobLink,282 };283 });284}285export function getSigninMethods(testAgent: TestAgent, email: string): Promise<string[]> {286 return testAgent287 .post("/identitytoolkit.googleapis.com/v1/accounts:createAuthUri")288 .send({ continueUri: "http://example.com/", identifier: email })289 .query({ key: "fake-api-key" })290 .then((res) => {291 expectStatusCode(200, res);292 return res.body.signinMethods;293 });294}295export function updateProjectConfig(testAgent: TestAgent, config: {}): Promise<void> {296 return testAgent297 .patch(`/emulator/v1/projects/${PROJECT_ID}/config`)298 .set("Authorization", "Bearer owner")299 .send(config)300 .then((res) => {301 expectStatusCode(200, res);302 });303}304export function updateAccountByLocalId(305 testAgent: TestAgent,306 localId: string,307 fields: {}308): Promise<void> {309 return testAgent310 .post("/identitytoolkit.googleapis.com/v1/accounts:update")311 .set("Authorization", "Bearer owner")312 .send({ localId, ...fields })313 .then((res) => {314 expectStatusCode(200, res);315 });316}317export function deleteAccount(testAgent: TestAgent, reqBody: {}): Promise<string> {318 return testAgent319 .post("/identitytoolkit.googleapis.com/v1/accounts:delete")320 .send(reqBody)321 .query({ key: "fake-api-key" })322 .then((res) => {323 expectStatusCode(200, res);324 expect(res.body).not.to.have.property("error");325 return res.body.kind;326 });...
agent.js
Source:agent.js
...15 * @param {Function|Server} app16 * @param {Object} options17 * @api public18 */19function TestAgent(app, options) {20 if (!(this instanceof TestAgent)) return new TestAgent(app, options);21 if (typeof app === 'function') app = http.createServer(app); // eslint-disable-line no-param-reassign22 if (options) this._ca = options.ca;23 Agent.call(this);24 this.app = app;25}26/**27 * Inherits from `Agent.prototype`.28 */29TestAgent.prototype.__proto__ = Agent.prototype;30// override HTTP verb methods31methods.forEach(function(method) {32 TestAgent.prototype[method] = function(url, fn) { // eslint-disable-line no-unused-vars33 var req = new Test(this.app, method.toUpperCase(), url);34 req.ca(this._ca);...
Using AI Code Generation
1var request = require('supertest');2describe('GET /', function() {3 it('should return 200 OK', function(done) {4 .get('/')5 .expect(200, done);6 });7});8var request = require('supertest');9describe('GET /', function() {10 it('should return 200 OK', function(done) {11 .get('/')12 .expect(200, done);13 });14});15var request = require('supertest');16describe('GET /', function() {17 it('should return 200 OK', function(done) {18 .get('/')19 .expect(200, done);20 });21});22var request = require('supertest');23describe('GET /', function() {24 it('should return 200 OK', function(done) {25 .get('/')26 .expect(200, done);27 });28});29var request = require('supertest');30describe('GET /', function() {31 it('should return 200 OK', function(done) {32 .get('/')33 .expect(200, done);34 });35});36var request = require('supertest');37describe('GET /', function() {38 it('should return 200 OK', function(done) {39 .get('/')40 .expect(200, done);41 });42});43var request = require('supertest');44describe('GET /', function() {45 it('should return 200 OK', function(done) {46 .get('/')47 .expect(200, done);48 });49});
Using AI Code Generation
1var test = require('supertest');2test.agent(app)3 .post('/login')4 .send({ username: 'username', password: 'password' })5 .expect(200)6 .end(function(err, res) {7 if (err) throw err;8 });
Using AI Code Generation
1var supertest = require('supertest');2var test = require('unit.js');3describe('GET /', function() {4 it('should return 200 OK', function(done) {5 .get('/')6 .expect(200)7 .end(function(err, res) {8 if (err) return done(err);9 test.value(res.body).is('Hello World');10 done();11 });12 });13});14var supertest = require('supertest');15var test = require('unit.js');16describe('GET /', function() {17 it('should return 200 OK', function(done) {18 .get('/')19 .expect(200)20 .end(function(err, res) {21 if (err) return done(err);22 test.value(res.body).is('Hello World');23 done();24 });25 });26});27var supertest = require('supertest');28var test = require('unit.js');29describe('GET /', function() {30 it('should return 200 OK', function(done) {31 .get('/')32 .expect(200)33 .end(function(err, res) {34 if (err) return done(err);35 test.value(res.body).is('Hello World');36 done();37 });38 });39});40var supertest = require('supertest');41var test = require('unit.js');42describe('GET /', function() {43 it('should return 200 OK', function(done) {44 .get('/')45 .expect(200)46 .end(function(err, res) {47 if (err) return done(err);48 test.value(res.body).is('Hello World');49 done();50 });51 });52});53var supertest = require('supertest');54var test = require('unit.js');
Using AI Code Generation
1var TestAgent = require('supertest').TestAgent;2var request = require('supertest');3var express = require('express');4var app = express();5var testAgent = request.agent(app);6describe('GET /', function () {7 it('respond with hello world', function (done) {8 .get('/')9 .expect('hello world')10 .end(done);11 });12});
Using AI Code Generation
1var request = require('supertest');2var test = require('unit.js');3var assert = require('assert');4describe('GET /', function() {5 it('respond with json', function(done) {6 .get('/')7 .expect('Content-Type', /json/)8 .expect(200)9 .end(function(err, res) {10 if (err) return done(err);11 test.value(res.body).hasHeader('content-type', 'application/json; charset=utf-8');12 test.value(res.body).hasHeader('content-length', '15');13 test.value(res.body).hasHeader('etag', 'W/"f-3Oz+V5Z5pR0jwOJcFQWYVQ"');14 test.value(res.body).hasHeader('date', 'Fri, 08 Apr 2016 11:56:59 GMT');15 test.value(res.body).hasHeader('connection', 'keep-alive');16 assert.equal(res.body.message, 'Hello World!');17 done();18 });19 });20});21var request = require('supertest');22var test = require('unit.js');23var assert = require('assert');24describe('GET /', function() {25 it('respond with json', function(done) {26 .get('/')27 .expect('Content-Type', /json/)28 .expect(200)29 .end(function(err, res) {30 if (err) return done(err);31 test.value(res.body).hasHeader('content-type', 'application/json; charset=utf-8');32 test.value(res.body).hasHeader('content-length', '15');33 test.value(res.body).hasHeader('etag', 'W/"f-3Oz+V5Z5pR0jwOJcFQWYVQ"');34 test.value(res.body).hasHeader('date', 'Fri, 08 Apr 2016 11:56:59 GMT');35 test.value(res.body).hasHeader('connection', 'keep-alive');36 assert.equal(res.body.message, 'Hello World!');37 done();38 });39 });40});
Using AI Code Generation
1var request = require('supertest');2var TestAgent = request.TestAgent;3var app = require('app');4var agent = new TestAgent(app);5var request = require('supertest');6var app = require('app');7var agent = request.agent(app);8var request = require('supertest');9var app = require('app');10var agent = request.agent(app, {jar: request.jar()});11var request = require('supertest');12var app = require('app');13var agent = request.agent(app, {jar: request.jar(), maxRedirects: 5});14var request = require('supertest');15var app = require('app');16var agent = request.agent(app, {jar: request.jar(), maxRedirects: 5});17var request = require('supertest');18var app = require('app');19var agent = request.agent(app, {jar: request.jar(), maxRedirects: 5});20var request = require('supertest');21var app = require('app');22var agent = request.agent(app, {jar: request.jar(), maxRedirects: 5});23var request = require('supertest');24var app = require('app');25var agent = request.agent(app, {jar: request.jar(), maxRedirects: 5});26var request = require('supertest');27var app = require('app');28var agent = request.agent(app, {jar: request.jar(), maxRedirects: 5});29var request = require('supertest');30var app = require('app');31var agent = request.agent(app, {jar: request.jar(), maxRedirects: 5});32var request = require('supertest');33var app = require('app');34var agent = request.agent(app, {jar: request.jar(), maxRedirects: 5});
Using AI Code Generation
1require('test-agent').attach(supertest);2require('test-agent').attach(supertest);3require('test-agent').attach(supertest);4require('test-agent').attach(supertest);5require('test-agent').attach(supertest);6require('test-agent').attach(supertest);7require('test-agent').attach(supertest);8require('test-agent').attach(supertest);9require('test-agent').attach(supertest);
Learn 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!!