How to use withRequest method in pact-foundation-pact

Best JavaScript code snippet using pact-foundation-pact

ApiClient.test.ts

Source:ApiClient.test.ts Github

copy

Full Screen

1import {InteractionObject, Pact} from "@pact-foundation/pact";2import * as path from "path";3import {meTracksResponse} from "./test_resources/me_tracks_response";4import {ApiClient, DepaginatedAlbum} from "./ApiClient";5import {meResponse} from "./test_resources/me_response";6import {TokenService} from "../account/TokenService";7import {instance, mock, when} from "ts-mockito";8import {meAlbumsResponse} from "./test_resources/me_albums_response";9import {ErrorHandlingFetch} from "./ErrorHandlingFetch";10import {MatcherResult} from "@pact-foundation/pact/dsl/matchers";11import {12 albumTracksPage2Response,13 albumTracksPage3Response,14 depaginatedAlbum,15 paginatedMeAlbumsResponse16} from "./test_resources/paginated_album_response";17import Spy = jasmine.Spy;18const mockServerPort = 8123;19jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;20describe("ApiClient", () => {21 const provider = new Pact({22 consumer: "snoutify",23 cors: false,24 dir: path.resolve(process.cwd(), "pacts"),25 port: mockServerPort,26 provider: "spotify",27 });28 let apiClient: ApiClient;29 let tokenService: TokenService;30 let fetchSpy: Spy;31 beforeAll(() => provider.setup());32 beforeEach(async () => {33 tokenService = mock(TokenService);34 when(tokenService.getToken()).thenReturn("real-access-token");35 const errorHandlingFetch = new ErrorHandlingFetch(window, tokenService);36 fetchSpy = spyOn(errorHandlingFetch, "fetch").and.callThrough();37 apiClient = new ApiClient(38 `http://localhost:${mockServerPort}`,39 errorHandlingFetch,40 instance(tokenService));41 await provider.removeInteractions();42 });43 describe("addToPlaylist", () => {44 beforeEach(async () => {45 const interaction: InteractionObject = {46 state: "with 3 albums",47 uponReceiving: "POST /v1/playlists/:id/tracks",48 withRequest: {49 method: "POST",50 path: "/v1/playlists/playlist-id/tracks",51 headers: {52 Authorization: "Bearer real-access-token",53 "Content-Type": "application/json;charset=utf-8",54 },55 body: {56 uris: [57 "spotify:track:track-id-1",58 "spotify:track:track-id-2",59 ]60 }61 },62 willRespondWith: {63 status: 201,64 }65 };66 await provider.addInteraction(preflightRequestFor(interaction));67 await provider.addInteraction(interaction);68 });69 it("adds tracks to the playlist", async () => {70 await apiClient.addToPlaylist("playlist-id", [71 "spotify:track:track-id-1",72 "spotify:track:track-id-2"73 ]);74 expect(fetchSpy.calls.argsFor(0)[0]).toEqual("error adding tracks to playlist");75 });76 });77 describe("createPlaylist", () => {78 beforeEach(async () => {79 const interaction: InteractionObject = {80 state: "with 3 albums",81 uponReceiving: "POST /v1/me/playlists",82 withRequest: {83 method: "POST",84 path: "/v1/me/playlists",85 headers: {86 Authorization: "Bearer real-access-token",87 "Content-Type": "application/json;charset=utf-8",88 },89 body: {90 name: "playlist-name",91 description: "playlist-description",92 public: false,93 }94 },95 willRespondWith: {96 status: 201,97 headers: {98 "Content-Type": "application/json",99 },100 body: {101 id: "new-playlist-id"102 }103 }104 };105 await provider.addInteraction(preflightRequestFor(interaction));106 await provider.addInteraction(interaction);107 });108 it("returns the playlist id", async () => {109 const id = await apiClient.createPlaylist("playlist-name", "playlist-description");110 expect(id).toEqual("new-playlist-id");111 expect(fetchSpy.calls.argsFor(0)[0]).toEqual("error creating playlist");112 });113 });114 describe("deleteAlbums", () => {115 beforeEach(async () => {116 const interaction: InteractionObject = {117 state: "with 3 albums",118 uponReceiving: "DELETE /v1/me/albums",119 withRequest: {120 method: "DELETE",121 path: "/v1/me/albums",122 query: "ids=album-1-id,album-2-id",123 headers: {124 Authorization: "Bearer real-access-token",125 },126 },127 willRespondWith: {128 status: 200,129 }130 };131 await provider.addInteraction(preflightRequestFor(interaction));132 await provider.addInteraction(interaction);133 });134 it("deletes the albums", async () => {135 await apiClient.deleteAlbums(["album-1-id", "album-2-id"]);136 expect(fetchSpy.calls.argsFor(0)[0]).toEqual("error deleting albums");137 });138 });139 describe("getAlbumCount", () => {140 beforeEach(async () => {141 const interaction: InteractionObject = {142 state: "with 3 albums",143 uponReceiving: "GET /v1/me/albums (count)",144 withRequest: {145 method: "GET",146 path: "/v1/me/albums",147 query: "offset=0&limit=1",148 headers: {149 Authorization: "Bearer real-access-token"150 }151 },152 willRespondWith: {153 status: 200,154 headers: {155 "Content-Type": "application/json",156 },157 body: meAlbumsResponse158 }159 };160 await provider.addInteraction(preflightRequestFor(interaction));161 await provider.addInteraction(interaction);162 });163 it("returns the number of albums", async () => {164 const count = await apiClient.getAlbumCount();165 expect(count).toEqual(3);166 expect(fetchSpy.calls.argsFor(0)[0]).toEqual("error retrieving album count");167 });168 });169 describe("getAlbumByOffset", () => {170 beforeEach(async () => {171 const interaction: InteractionObject = {172 state: "with 3 albums",173 uponReceiving: "GET /v1/me/albums (by offset)",174 withRequest: {175 method: "GET",176 path: "/v1/me/albums",177 query: "offset=0&limit=1",178 headers: {179 Authorization: "Bearer real-access-token"180 }181 },182 willRespondWith: {183 status: 200,184 headers: {185 "Content-Type": "application/json",186 },187 body: meAlbumsResponse188 }189 };190 await provider.addInteraction(preflightRequestFor(interaction));191 await provider.addInteraction(interaction);192 });193 it("returns the album", async () => {194 const album = await apiClient.getAlbumByOffset(0);195 expect(album).toEqual({196 id: "album-1-id",197 name: "album-1-name",198 artists: [199 {name: "artist-1"},200 {name: "artist-2"},201 ],202 images: [203 {width: 480, height: 480, url: "/images/album-1.png"}204 ],205 tracks: {206 items: [207 {id: "album-1-track-1"},208 {id: "album-1-track-2"},209 {id: "album-1-track-3"},210 ],211 total: 3,212 next: null,213 }214 } as DepaginatedAlbum);215 expect(fetchSpy.calls.argsFor(0)[0]).toEqual("error retrieving album");216 });217 });218 describe("getAlbumByOffset (with pagination)", () => {219 beforeEach(async () => {220 const paginatedMeAlbums: InteractionObject = {221 state: "with paginated album",222 uponReceiving: "GET /v1/me/albums (paginated)",223 withRequest: {224 method: "GET",225 path: "/v1/me/albums",226 query: "offset=0&limit=1",227 headers: {228 Authorization: "Bearer real-access-token"229 }230 },231 willRespondWith: {232 status: 200,233 headers: {234 "Content-Type": "application/json",235 },236 body: paginatedMeAlbumsResponse237 }238 };239 const albumTracksPage2: InteractionObject = {240 state: "with paginated album",241 uponReceiving: "GET /v1/albums/album-4-id/tracks (page 2)",242 withRequest: {243 method: "GET",244 path: "/v1/albums/album-4-id/tracks",245 query: "offset=50&limit=50",246 headers: {247 Authorization: "Bearer real-access-token"248 }249 },250 willRespondWith: {251 status: 200,252 headers: {253 "Content-Type": "application/json",254 },255 body: albumTracksPage2Response256 }257 };258 const albumTracksPage3: InteractionObject = {259 state: "with paginated album",260 uponReceiving: "GET /v1/albums/album-4-id/tracks (page 3)",261 withRequest: {262 method: "GET",263 path: "/v1/albums/album-4-id/tracks",264 query: "offset=100&limit=50",265 headers: {266 Authorization: "Bearer real-access-token"267 }268 },269 willRespondWith: {270 status: 200,271 headers: {272 "Content-Type": "application/json",273 },274 body: albumTracksPage3Response275 }276 };277 await provider.addInteraction(preflightRequestFor(paginatedMeAlbums));278 await provider.addInteraction(paginatedMeAlbums);279 await provider.addInteraction(preflightRequestFor(albumTracksPage2));280 await provider.addInteraction(albumTracksPage2);281 await provider.addInteraction(preflightRequestFor(albumTracksPage3));282 await provider.addInteraction(albumTracksPage3);283 });284 it("returns the album", async () => {285 const album = await apiClient.getAlbumByOffset(0);286 expect(album).toEqual(depaginatedAlbum);287 expect(fetchSpy.calls.argsFor(0)[0]).toEqual("error retrieving album");288 expect(fetchSpy.calls.argsFor(1)[0]).toEqual("error retrieving album tracks");289 expect(fetchSpy.calls.argsFor(2)[0]).toEqual("error retrieving album tracks");290 });291 });292 describe("getTrackCount", () => {293 beforeEach(async () => {294 const interaction: InteractionObject = {295 state: "with 5 tracks",296 uponReceiving: "GET /v1/me/tracks",297 withRequest: {298 method: "GET",299 path: "/v1/me/tracks",300 query: "offset=0&limit=1",301 headers: {302 Authorization: "Bearer real-access-token"303 }304 },305 willRespondWith: {306 status: 200,307 headers: {308 "Content-Type": "application/json",309 },310 body: meTracksResponse311 }312 };313 await provider.addInteraction(preflightRequestFor(interaction));314 await provider.addInteraction(interaction);315 });316 it("returns the number of tracks", async () => {317 const count = await apiClient.getTrackCount();318 expect(count).toEqual(5);319 expect(fetchSpy.calls.argsFor(0)[0]).toEqual("error retrieving track count");320 });321 });322 describe("getUsername", () => {323 beforeEach(async () => {324 const interaction: InteractionObject = {325 state: "with test user",326 uponReceiving: "GET /v1/me",327 withRequest: {328 method: "GET",329 path: "/v1/me",330 headers: {331 Authorization: "Bearer real-access-token"332 }333 },334 willRespondWith: {335 status: 200,336 headers: {337 "Content-Type": "application/json",338 },339 body: meResponse340 }341 };342 await provider.addInteraction(preflightRequestFor(interaction));343 await provider.addInteraction(interaction);344 });345 it("returns the username", async () => {346 const username = await apiClient.getUsername();347 expect(username).toEqual("Test User");348 expect(fetchSpy.calls.argsFor(0)[0]).toEqual("error retrieving username");349 });350 });351 describe("getUsername (error)", () => {352 beforeEach(async () => {353 const interaction: InteractionObject = {354 state: "endpoints returning 500",355 uponReceiving: "GET /v1/me (error)",356 withRequest: {357 method: "GET",358 path: "/v1/me",359 headers: {360 Authorization: "Bearer real-access-token"361 }362 },363 willRespondWith: {364 status: 500,365 }366 };367 await provider.addInteraction(preflightRequestFor(interaction));368 await provider.addInteraction(interaction);369 });370 it("throws an error", async () => {371 try {372 await apiClient.getUsername();373 fail("should have thrown an error");374 } catch (e) {375 expect(e.message).toEqual("error retrieving username: 500 Internal Server Error");376 }377 });378 });379 afterEach(() => provider.verify());380 afterAll(() => provider.finalize());381});382function preflightRequestFor(interaction: InteractionObject): InteractionObject {383 const headers = interaction.withRequest.headers;384 const allowedHeaders = headers ? filterHeaders(headers).join(", ").toLowerCase() : "*";385 const maybeQuery = interaction.withRequest.query ? `?${interaction.withRequest.query}` : "";386 return {387 state: interaction.state,388 uponReceiving: `OPTIONS ${interaction.withRequest.path}${maybeQuery} (${interaction.withRequest.method})`,389 withRequest: {390 method: "OPTIONS",391 path: interaction.withRequest.path,392 query: interaction.withRequest.query,393 headers: {394 "Origin": "http://localhost",395 "Access-Control-Request-Method": interaction.withRequest.method,396 "Access-Control-Request-Headers": `${allowedHeaders}`,397 }398 },399 willRespondWith: {400 status: 200,401 headers: {402 "Access-Control-Allow-Origin": 'http://localhost',403 "Access-Control-Allow-Credentials": "true",404 "Access-Control-Allow-Headers": `${allowedHeaders}`,405 },406 }407 };408}409// not what the spec says, but what JSDOM does...410function filterHeaders(headers: { [name: string]: string | MatcherResult }) {411 const nope = ["content-type"];412 return Object.keys(headers)413 .filter(header => nope.indexOf(header.toLowerCase()) === -1);...

Full Screen

Full Screen

pactInteractions.ts

Source:pactInteractions.ts Github

copy

Full Screen

...118) =>119 newInteraction()120 .given(givenName)121 .uponReceiving(content.uponReceiving)122 .withRequest(replaceParams(content.withRequest))...

Full Screen

Full Screen

dispatcher.js

Source:dispatcher.js Github

copy

Full Screen

...8 var req = request(method, url)9 .accept(accept || 'json')10 .set('X-Requested-With', 'XMLHttpRequest') // send to symfony11 if (withRequest) {12 withRequest(req);13 }14 var promise = new Promise(function (fulfill, reject) {15 req16 .send(body)17 .end(function(err, response) {18 if (response.ok) {19 fulfill(response);20 } else {21 err.response = response;22 reject(err);23 }24 });25 26 });27 return promise;28 };29 this.send = function(method, url, body, accept, withRequest) {30 var d = $.Deferred();31 if (_.isArray(url)) {32 url = '/'+url.join('/');33 }34 var req = request(method, url)35 .accept(accept || 'json');36 if (withRequest) {37 withRequest(req);38 }39 req40 .send(body)41 .end(function(err, response) {42 if (response.ok) {43 d.resolve(response);44 } else {45 d.reject(err, response);46 }47 });48 return d.promise();49 };50 };51 return new Dispatcher();...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Matchers } from "@pact-foundation/pact";2import { withPact } from "@pact-foundation/pact";3import { get } from "axios";4import path from "path";5const { like } = Matchers;6const provider = {7};8describe("test2", () => {9 it("returns a successful body", () => {10 return withPact({11 dir: path.resolve(process.cwd(), "pacts"),12 log: path.resolve(process.cwd(), "logs", "mockserver-integration.log"),13 })14 .then((pact) => {15 pact.addInteraction({16 withRequest: {17 headers: {18 },19 },20 willRespondWith: {21 headers: {22 },23 body: {24 users: like([25 {26 },27 },28 },29 });30 return pact.verify();31 })32 .then(() => {33 })34 .then((response) => {35 expect(response.data).toEqual({36 {37 },38 });39 });40 });41});42import { Matchers } from "@pact-foundation/pact";43import { withPact } from "@pact-foundation/p

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run pact-foundation-pact automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful