How to use uponReceiving method in pact-foundation-pact

Best JavaScript code snippet using pact-foundation-pact

pact.test.js

Source:pact.test.js Github

copy

Full Screen

1import Pact, {Matchers} from 'pact'2import path from 'path'3import {get} from './lib/http'4import {post} from './lib/http'5describe('set up pact', () => {6 const PACT_SERVER_PORT = 124007 const PACT_SPECIFICATION_VERSION = 28 const PACT_HOST = 'http://localhost:' + PACT_SERVER_PORT9 const provider = Pact({10 consumer: 'Frontend',11 provider: 'Backend',12 port: PACT_SERVER_PORT,13 spec: PACT_SPECIFICATION_VERSION,14 log: path.resolve(process.cwd(), './__pacts__/logs', 'pact-integration.log'),15 dir: path.resolve(process.cwd(), './__pacts__/pacts')16 })17 beforeAll(() => provider.setup())18 afterAll(() => provider.finalize())19 describe('returns a welcome message', () => {20 const expected = {message: 'Welcome to backend API!'}21 beforeAll(() => provider.addInteraction({22 uponReceiving: 'a request for getting welcome message',23 withRequest: {24 method: 'GET',25 path: '/api',26 headers: { 'Accept': 'application/json' }27 },28 willRespondWith: {29 status: 200,30 headers: { 'Content-Type': 'application/json; charset=utf-8' },31 body: expected32 }33 })34 )35 36 it('returns a list of events', async () => {37 const result = await get(PACT_HOST + '/api', {headers: { 'Accept': 'application/json' }})38 39 expect(result).toEqual({...expected, status: 200})40 })41 it('successfully verifies', () => provider.verify())42 })43 // Forum44 describe('returns a forum thread', () => {45 46 const headers = {47 'Accept': 'application/json',48 'Authorization': 'eyJhbGciOiJIUzI1NiJ9.eyJmaXJzdE5hbWUiOiJGTnVzZXIxIiwiZW1haWwiOiJ1c2VyMUB1c2VyLmNvbSIsInJvbGUiOiJVU0VSIiwidXNlcklkIjoiNWEzMjY1ZTM3YTdkNTUwMDFkOGEyZTZlIn0.ikrvRAg6kTZItYXzxC0CyBSrGXryxTp95QUvQI9nYGI'49 };50 beforeAll(() => provider.addInteraction({51 uponReceiving: 'returns a forum thread',52 withRequest: {53 method: 'GET',54 path: '/api/forum/thread',55 headers: headers56 },57 willRespondWith: {58 status: 200,59 headers: { 'Content-Type': 'application/json; charset=utf-8' },60 body: Matchers.eachLike(61 {62 "title": "How to configure the flux capasitor in a Samsung 420? thread 0 . 0",63 "date": "2017-12-18T12:44:45.028Z"64 }65 )66 }67 })68 )69 70 it('returns a forum thread', async () => {71 const result = await get(PACT_HOST + '/api/forum/thread', {headers: headers})72 73 const expected = [74 {75 "title": "How to configure the flux capasitor in a Samsung 420? thread 0 . 0",76 "date": "2017-12-18T12:44:45.028Z"77 }78 ]79 expected.status = 20080 expect(result).toEqual(expected)81 })82 it('successfully verifies', () => provider.verify())83 })84 // LOGIN TESTS85 describe('admin can login in', () => {86 const expected = {87 error: false,88 token: 'eyJhbGciOiJIUzI1NiJ9.eyJmaXJzdE5hbWUiOiJBZG1pbiIsImVtYWlsIjoiYWRtaW5AYWRtaW4ubnUiLCJyb2xlIjoiQURNSU4ifQ.jcQEXVDj3HZADGaLRRCAIRpLr7anqmWY-J6Ms9yUdgE'89 }90 beforeAll(() => provider.addInteraction({91 uponReceiving: 'login request with admin login',92 withRequest: {93 method: 'POST',94 path: '/api/user/login',95 headers: {96 'Content-Type': 'application/json'97 },98 body: { 'email': 'admin@admin.nu', 'password': 'admin' }99 },100 willRespondWith: {101 status: 200,102 headers: { 'Content-Type': 'application/json; charset=utf-8' },103 body: {104 error: false,105 token: Matchers.somethingLike('eyJhbGciOiJIUzI1NiJ9.eyJmaXJzdE5hbWUiOiJBZG1pbiIsImVtYWlsIjoiYWRtaW5AYWRtaW4ubnUiLCJyb2xlIjoiQURNSU4ifQ.jcQEXVDj3HZADGaLRRCAIRpLr7anqmWY-J6Ms9yUdgE')106 }107 }108 })109 )110 it('returns a matching token', async () => {111 const result = await post(PACT_HOST + '/api/user/login', {headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({email: 'admin@admin.nu', password: 'admin'})})112 expect(result).toEqual({...expected, status: 200})113 })114 it('successfully verifies', () => provider.verify())115 })116 117 describe('company rep can login in', () => {118 const expected = { error: false, token: "eyJhbGciOiJIUzI1NiJ9.eyJmaXJzdE5hbWUiOiJGTlNhbXN1bmdSZXAiLCJlbWFpbCI6InJlcEBzYW1zdW5nLmNvbSIsInJvbGUiOiJDT01QQU5ZX1JFUCIsImNvbXBhbnlJZCI6IjVhNGI1MWJlZWJlYThiMDAyOTRhYzkzYSJ9.amXegC52E3M1F3A4P90FOtFYJBNEz_Ot9gyvqr3YCho" }119 beforeAll(() => provider.addInteraction({120 uponReceiving: 'login request with company rep login',121 withRequest: {122 method: 'POST',123 path: '/api/user/login',124 headers: { 'Content-Type': 'application/json' },125 body: { 'email': 'rep@samsung.com', 'password': 'password' }126 },127 willRespondWith: {128 status: 200,129 headers: { 'Content-Type': 'application/json; charset=utf-8' },130 body: {131 error: false,132 token: Matchers.somethingLike('eyJhbGciOiJIUzI1NiJ9.eyJmaXJzdE5hbWUiOiJGTlNhbXN1bmdSZXAiLCJlbWFpbCI6InJlcEBzYW1zdW5nLmNvbSIsInJvbGUiOiJDT01QQU5ZX1JFUCIsImNvbXBhbnlJZCI6IjVhNGI1MWJlZWJlYThiMDAyOTRhYzkzYSJ9.amXegC52E3M1F3A4P90FOtFYJBNEz_Ot9gyvqr3YCho')133 }134 }135 })136 )137 it('returns a matching token', async () => {138 const result = await post(PACT_HOST + '/api/user/login', {headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({email: 'rep@samsung.com', password: "password"})})139 expect(result).toEqual({...expected, status: 200})140 })141 })142 describe('user can login in', () => {143 const expected = { error: false, token: "eyJhbGciOiJIUzI1NiJ9.eyJmaXJzdE5hbWUiOiJGTnVzZXIyOSIsImVtYWlsIjoidXNlcjI5QHVzZXIuY29tIiwicm9sZSI6IlVTRVIifQ.w2_IERnUUMbnSeGHSjNv0CMIEC-YSA4UMksRXdv5g-8" }144 beforeAll(() => provider.addInteraction({145 uponReceiving: 'login request with regular user login',146 withRequest: {147 method: 'POST',148 path: '/api/user/login',149 headers: { 'Content-Type': 'application/json' },150 body: { 'email': 'user29@user.com', 'password': 'password' }151 },152 willRespondWith: {153 status: 200,154 headers: { 'Content-Type': 'application/json; charset=utf-8' },155 body: {156 error: false,157 token: Matchers.somethingLike('eyJhbGciOiJIUzI1NiJ9.eyJmaXJzdE5hbWUiOiJGTnVzZXIyOSIsImVtYWlsIjoidXNlcjI5QHVzZXIuY29tIiwicm9sZSI6IlVTRVIifQ.w2_IERnUUMbnSeGHSjNv0CMIEC-YSA4UMksRXdv5g-8')158 }159 }160 })161 )162 it('returns a matching token', async () => {163 const result = await post(PACT_HOST + '/api/user/login', {headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({email: 'user29@user.com', password: "password"})})164 expect(result).toEqual({...expected, status: 200})165 })166 })167// TEST 2 START168 describe('returns all products', () => {169 const headers = {170 'Accept': 'application/json',171 'Authorization': 'eyJhbGciOiJIUzI1NiJ9.eyJmaXJzdE5hbWUiOiJGTnVzZXIyOSIsImVtYWlsIjoidXNlcjI5QHVzZXIuY29tIiwicm9sZSI6IlVTRVIifQ.w2_IERnUUMbnSeGHSjNv0CMIEC-YSA4UMksRXdv5g-8'172 }173 beforeAll(() => provider.addInteraction({174 uponReceiving: 'a request for getting products',175 withRequest: {176 method: 'GET',177 path: '/api/product',178 headers179 },180 willRespondWith: {181 status: 200,182 headers: { 'Content-Type': 'application/json; charset=utf-8' },183 body: Matchers.eachLike({184 "_id": "5a280388169758001ce1fd6b",185 "name": "Samsung Mobile Phone 0",186 "category": "5a280387169758001ce1fd5f",187 "rating": [],188 "materials": ["5a280388169758001ce1fd69"]189 })190 }191 })192 )193 it('returns a list of events', async () => {194 const result = await get(PACT_HOST + '/api/product', {headers})195 const expected = [196 {197 "_id": "5a280388169758001ce1fd6b",198 "name": "Samsung Mobile Phone 0",199 "category": "5a280387169758001ce1fd5f",200 "rating": [],201 "materials": ["5a280388169758001ce1fd69"]202 }203 ]204 expected.status = 200 // fix for ugly mapping of response status205 expect(result).toEqual(expected)206 })207 it('successfully verifies', () => provider.verify())208 })209// TEST 2 END210 describe('returns an error if no token in header on auth route', () => {211 const expected = {message: 'There was no token in the header', error: true }212 beforeAll(() => provider.addInteraction({213 uponReceiving: 'a request without auth header on authed route',214 withRequest: {215 method: 'GET',216 path: '/api/user/products',217 headers: { 'Accept': 'application/json' }218 },219 willRespondWith: {220 status: 401,221 headers: { 'Content-Type': 'application/json; charset=utf-8' },222 body: expected223 }224 })225 )226 it('returns an error', async () => {227 const result = await get(PACT_HOST + '/api/user/products', {headers: { 'Accept': 'application/json' }})228 expect(result).toEqual({...expected, status: 401})229 })230 })231 /*232 // Testing Rating233 describe('Create a rating', () => {234 const headers = {235 'Content-Type': 'application/json',236 'Authorization': 'eyJhbGciOiJIUzI1NiJ9.eyJmaXJzdE5hbWUiOiJGTnVzZXIyOSIsImVtYWlsIjoidXNlcjI5QHVzZXIuY29tIiwicm9sZSI6IlVTRVIifQ.w2_IERnUUMbnSeGHSjNv0CMIEC-YSA4UMksRXdv5g-8'237 };238 239 beforeAll(() => provider.addInteraction({240 uponReceiving: 'a request for creating a rating',241 withRequest: {242 method: 'POST',243 path: '/api/product/material/5a2838e4407de3001da76d72/rating',244 headers,245 body: { 'rating': 4 }246 },247 willRespondWith: {248 status: 201,249 headers: { 'Content-Type': 'application/json; charset=utf-8' },250 body: {251 "_id": "5a2838e4407de3001da76d72",252 "name": "manual",253 "originalname": "components.pdf",254 "filename": "e506a9172af9259843342dc44c58f763",255 "path": "src/lib/seed/e506a9172af9259843342dc44c58f763",256 "size": 33600,257 "mimetype": "application/pdf",258 "__v": 2,259 "avgRating": 4,260 "rating": [261 {262 "_id": "5a283ba1e892b9001e44fd6e",263 "userid": "5a2838d7407de3001da76d00",264 "materialid": "5a2838e4407de3001da76d72",265 "rating": 4266 },267 {268 "_id": "5a2846614bd89f001ee98d36",269 "userid": "5a2838d7407de3001da76d1e",270 "materialid": "5a2838e4407de3001da76d72",271 "rating": 4272 }273 ]274 }275 }276 })277 );278 const expected = {279 "_id": "5a2838e4407de3001da76d72",280 "name": "manual",281 "originalname": "components.pdf",282 "filename": "e506a9172af9259843342dc44c58f763",283 "path": "src/lib/seed/e506a9172af9259843342dc44c58f763",284 "size": 33600,285 "mimetype": "application/pdf",286 "__v": 2,287 "avgRating": 4,288 "rating": [289 {290 "_id": "5a283ba1e892b9001e44fd6e",291 "userid": "5a2838d7407de3001da76d00",292 "materialid": "5a2838e4407de3001da76d72",293 "rating": 4294 },295 {296 "_id": "5a2846614bd89f001ee98d36",297 "userid": "5a2838d7407de3001da76d1e",298 "materialid": "5a2838e4407de3001da76d72",299 "rating": 4300 }301 ]302 };303 it('returns a matching rating', async () => {304 const result = await post(PACT_HOST + '/api/product/material/5a2838e4407de3001da76d72/rating',305 {headers: headers, body: JSON.stringify({rating: 4})});306 expect(result).toEqual({...expected, status: 201})307 })308 })309 310 describe('Return a rating', () => {311 const headers = {312 'Accept': 'application/json',313 'Authorization': 'eyJhbGciOiJIUzI1NiJ9.eyJmaXJzdE5hbWUiOiJGTnVzZXIyOSIsImVtYWlsIjoidXNlcjI5QHVzZXIuY29tIiwicm9sZSI6IlVTRVIifQ.w2_IERnUUMbnSeGHSjNv0CMIEC-YSA4UMksRXdv5g-8'314 };315 beforeAll(() => provider.addInteraction({316 uponReceiving: 'a request for getting a rating',317 withRequest: {318 method: 'GET',319 path: '/api/product/material/5a2838e4407de3001da76d72/rating',320 headers321 },322 willRespondWith: {323 status: 200,324 headers: { 'Content-Type': 'application/json; charset=utf-8' },325 body: Matchers.eachLike(326 {327 "_id": "5a283ba1e892b9001e44fd6e",328 "userid": "5a2838d7407de3001da76d00",329 "materialid": "5a2838e4407de3001da76d72",330 "rating": 4331 }332 )333 }334 })335 );336 337 it('returns a list of ratings', async () => {338 const result = await get(PACT_HOST + '/api/product/material/5a2838e4407de3001da76d72/rating', {headers});339 const expected =[340 {341 "_id": "5a283ba1e892b9001e44fd6e",342 "userid": "5a2838d7407de3001da76d00",343 "materialid": "5a2838e4407de3001da76d72",344 "rating": 4345 }];346 expected.status = 200; // fix for ugly mapping of response status347 expect(result).toEqual(expected)348 });349 it('successfully verifies', () => provider.verify())350 })351 */...

Full Screen

Full Screen

pacts.slow.test.js

Source:pacts.slow.test.js Github

copy

Full Screen

1const fs = require('fs');2const request = require('supertest');3const app = require('../app');4describe.skip('Pact contracts generation for stubs', () => {5 const generatedPactFilepath = './generatedTestPacts/some-consumer-some-provider.json';6 beforeEach(async () => {7 try {8 fs.unlinkSync(generatedPactFilepath);9 } catch (e) {}10 await request(app).delete('/stubs');11 });12 it('does not generate a contract for a stub that does not have contract details setup', async () => {13 await request(app)14 .post('/stubs')15 .send({ requestMatcher: { url: '/john' } });16 const response = await request(app).post('/generate-pact').send({ consumer: 'some-consumer' });17 expect(response.statusCode).toEqual(200);18 expect(() =>19 JSON.parse(fs.readFileSync(generatedPactFilepath, { encoding: 'utf8' }).toString())20 ).toThrowError(/no such file or directory/);21 });22 it('generates a contract for the stub created', async () => {23 const state = 'in a given state';24 const uponReceiving = 'receiving some request';25 const providerName = 'some-provider';26 await request(app)27 .post('/stubs')28 .send({ requestMatcher: { url: '/john' }, contract: { state, uponReceiving, providerName } });29 const response = await request(app).post('/generate-pact').send({ consumer: 'some-consumer' });30 expect(response.statusCode).toEqual(200);31 const pact = JSON.parse(32 fs.readFileSync(generatedPactFilepath, { encoding: 'utf8' }).toString()33 );34 expect(pact).toEqual(35 aPactWithStructure({ url: '/john' }, { state, uponReceiving, providerName })36 );37 });38 it('generates a contract just for the stub with the contract details set', async () => {39 const state = 'some other state';40 const uponReceiving = 'upon whatevere';41 const providerName = 'some-provider';42 await request(app)43 .post('/stubs')44 .send({45 requestMatcher: { url: '/some-url' },46 contract: { state, uponReceiving, providerName }47 });48 await request(app)49 .post('/stubs')50 .send({ requestMatcher: { url: '/some-other-url' } });51 const response = await request(app).post('/generate-pact').send({ consumer: 'some-consumer' });52 expect(response.statusCode).toEqual(200);53 const pact = JSON.parse(54 fs.readFileSync(generatedPactFilepath, { encoding: 'utf8' }).toString()55 );56 expect(pact).toEqual(57 aPactWithStructure({ url: '/some-url' }, { state, uponReceiving, providerName })58 );59 });60 it('plays the interaction with the right method', async () => {61 const state = 'in a given state';62 const uponReceiving = 'receiving some request';63 const providerName = 'some-provider';64 await request(app)65 .post('/stubs')66 .send({67 requestMatcher: { url: '/john', method: 'POST' },68 contract: { state, uponReceiving, providerName }69 });70 const response = await request(app).post('/generate-pact').send({ consumer: 'some-consumer' });71 expect(response.statusCode).toEqual(200);72 const pact = JSON.parse(73 fs.readFileSync(generatedPactFilepath, { encoding: 'utf8' }).toString()74 );75 expect(pact).toEqual(76 aPactWithStructure({ url: '/john', method: 'POST' }, { state, uponReceiving, providerName })77 );78 });79 it('sets up the right body given the stub response body', async () => {80 const state = 'in a given state';81 const uponReceiving = 'receiving some request';82 const providerName = 'some-provider';83 await request(app)84 .post('/stubs')85 .send({86 requestMatcher: { url: '/stuff' },87 response: { body: { msg: `hello, how's it going` } },88 contract: { state, uponReceiving, providerName }89 });90 const response = await request(app).post('/generate-pact').send({ consumer: 'some-consumer' });91 expect(response.statusCode).toEqual(200);92 const pact = JSON.parse(93 fs.readFileSync(generatedPactFilepath, { encoding: 'utf8' }).toString()94 );95 expect(pact).toEqual(96 aPactWithStructure(97 { url: '/stuff', body: { msg: `hello, how's it going` } },98 { state, uponReceiving, providerName }99 )100 );101 });102 it('sets up the right status code', async () => {103 const state = 'in a given state';104 const uponReceiving = 'receiving some request';105 const providerName = 'some-provider';106 await request(app)107 .post('/stubs')108 .send({109 requestMatcher: { url: '/stuff' },110 response: { body: { msg: `hello, how's it going` }, statusCode: 404 },111 contract: { state, uponReceiving, providerName }112 });113 const response = await request(app).post('/generate-pact').send({ consumer: 'some-consumer' });114 expect(response.statusCode).toEqual(200);115 const pact = JSON.parse(116 fs.readFileSync(generatedPactFilepath, { encoding: 'utf8' }).toString()117 );118 expect(pact).toEqual(119 aPactWithStructure(120 { url: '/stuff', body: { msg: `hello, how's it going` }, statusCode: 404 },121 { state, uponReceiving, providerName }122 )123 );124 });125 it('sets up the right content type', async () => {126 const state = 'in a given state';127 const uponReceiving = 'receiving some request';128 const providerName = 'some-provider';129 await request(app)130 .post('/stubs')131 .send({132 requestMatcher: { url: '/stuff' },133 response: {134 body: `hello, how's it going`,135 type: 'text'136 },137 contract: { state, uponReceiving, providerName }138 });139 const response = await request(app).post('/generate-pact').send({ consumer: 'some-consumer' });140 expect(response.statusCode).toEqual(200);141 const pact = JSON.parse(142 fs.readFileSync(generatedPactFilepath, { encoding: 'utf8' }).toString()143 );144 expect(pact).toEqual(145 aPactWithStructure(146 { url: '/stuff', body: `hello, how's it going`, contentType: 'text/plain' },147 { state, uponReceiving, providerName }148 )149 );150 });151 it('sets up multiple interactions for the same provider', async () => {152 const state1 = 'in a given state 123';153 const uponReceiving1 = 'receiving some request 123';154 const state2 = 'in a given state 321';155 const uponReceiving2 = 'receiving some request 321';156 const providerName = 'some-provider';157 await request(app)158 .post('/stubs')159 .send({160 requestMatcher: { url: '/stuff' },161 response: {162 body: `hello, how's it going`,163 type: 'text'164 },165 contract: { state: state1, uponReceiving: uponReceiving1, providerName }166 });167 await request(app)168 .post('/stubs')169 .send({170 requestMatcher: { url: '/another-url', method: 'POST' },171 response: {172 body: { mgs: 'this be json' },173 statusCode: 404174 },175 contract: { state: state2, uponReceiving: uponReceiving2, providerName }176 });177 const response = await request(app).post('/generate-pact').send({ consumer: 'some-consumer' });178 expect(response.statusCode).toEqual(200);179 const pact = JSON.parse(180 fs.readFileSync(generatedPactFilepath, { encoding: 'utf8' }).toString()181 );182 expect(pact.consumer).toEqual({ name: 'some-consumer' });183 expect(pact.provider).toEqual({ name: providerName });184 expect(pact.interactions).toEqual(185 expect.arrayContaining([186 {187 description: uponReceiving1,188 providerState: state1,189 request: {190 method: 'GET',191 path: '/stuff'192 },193 response: {194 status: 200,195 headers: {196 'Content-Type': 'text/plain'197 },198 body: `hello, how's it going`199 },200 metadata: null201 },202 {203 description: uponReceiving2,204 providerState: state2,205 request: {206 method: 'POST',207 path: '/another-url'208 },209 response: {210 status: 404,211 headers: {212 'Content-Type': 'application/json'213 },214 body: { mgs: 'this be json' }215 },216 metadata: null217 }218 ])219 );220 });221 describe('multiple providers', () => {222 const contract1 = './generatedTestPacts/some-consumer-some-provider1.json';223 const contract2 = './generatedTestPacts/some-consumer-some-provider2.json';224 beforeEach(async () => {225 try {226 fs.unlinkSync(contract1);227 fs.unlinkSync(contract2);228 } catch (e) {}229 await request(app).delete('/stubs');230 });231 it('generates a contract for each different provider-consumer pair', async () => {232 const state = 'some other state';233 const uponReceiving = 'upon whatevere';234 const providerName1 = 'some-provider1';235 const providerName2 = 'some-provider2';236 await request(app)237 .post('/stubs')238 .send({239 requestMatcher: { url: '/some-url' },240 contract: { state, uponReceiving, providerName: providerName1 }241 });242 await request(app)243 .post('/stubs')244 .send({245 requestMatcher: { url: '/some-other-url' },246 contract: { state, uponReceiving, providerName: providerName2 }247 });248 const response = await request(app)249 .post('/generate-pact')250 .send({ consumer: 'some-consumer' });251 expect(response.statusCode).toEqual(200);252 const pact1 = JSON.parse(253 fs254 .readFileSync(contract1, {255 encoding: 'utf8'256 })257 .toString()258 );259 const pact2 = JSON.parse(260 fs261 .readFileSync(contract2, {262 encoding: 'utf8'263 })264 .toString()265 );266 expect(pact1).toEqual(267 aPactWithStructure(268 { url: '/some-url' },269 { state, uponReceiving, providerName: providerName1 }270 )271 );272 expect(pact2).toEqual(273 aPactWithStructure(274 { url: '/some-other-url' },275 { state, uponReceiving, providerName: providerName2 }276 )277 );278 });279 });280});281function aPactWithStructure(282 { url, method = 'GET', body = {}, statusCode = 200, contentType = 'application/json' },283 { state, uponReceiving, providerName }284) {285 return {286 consumer: {287 name: 'some-consumer'288 },289 provider: {290 name: providerName291 },292 interactions: [293 {294 description: uponReceiving,295 providerState: state,296 request: {297 method,298 path: url299 },300 response: {301 status: statusCode,302 headers: {303 'Content-Type': contentType304 },305 body306 },307 metadata: null308 }309 ],310 metadata: {311 pactSpecification: {312 version: '2.0.0'313 }314 }315 };316}317function aPactWithMultipleInteractions(theInteractions, providerName) {318 const interactions = theInteractions.map((interaction) => ({319 description: interaction.uponReceiving,320 providerState: interaction.state,321 request: {322 method: interaction.method,323 path: interaction.url324 },325 response: {326 status: interaction.statusCode,327 headers: {328 'Content-Type': interaction.contentType329 },330 body: interaction.body331 }332 }));333 return {334 consumer: {335 name: 'some-consumer'336 },337 provider: {338 name: providerName339 },340 interactions,341 metadata: {342 pactSpecification: {343 version: '2.0.0'344 }345 }346 };...

Full Screen

Full Screen

ReviewsClient.test.js

Source:ReviewsClient.test.js Github

copy

Full Screen

1const ReviewsClient = require('../utils/ReviewsClient')2const { Pact, Matchers } = require('@pact-foundation/pact')3// Excercise uncomment:4const CONSUMER = 'Movies' // What is the name of the consumer??5const PROVIDER = 'Reviews' // What is the name of the provider??6const MOCK_PROVIDER_PORT = 3002 // What is the provider's port details??7describe('Reviews contract tests', () => {8 let provider9 beforeAll(async () => {10 provider = new Pact({11 consumer: CONSUMER,12 provider: PROVIDER,13 port: MOCK_PROVIDER_PORT,14 log: process.cwd() + '/logs/pact.log',15 dir: process.cwd() + '/pacts',16 logLevel: 'INFO',17 spec: 218 })19 await provider.setup()20 })21 afterAll(async () => {22 await provider.finalize()23 })24 describe('Reviews client tests', () => {25 test('should receive movie statistics for specified movies', async () => {26 await provider.addInteraction({27 state: 'Has reviews statistics for movie',28 uponReceiving: 'a request for all movies stats summary',29 withRequest: {30 method: 'GET',31 path: `/stats`32 },33 willRespondWith: {34 status: 200,35 headers: { 'Content-Type': 'application/json; charset=utf-8' },36 body: Matchers.eachLike(37 {38 'id': Matchers.like('1'),39 'totalReviews': Matchers.like(100),40 'averageRating': Matchers.like(7.5)41 }42 )43 }44 })45 const result = await ReviewsClient.getAllMoviesStatistics()46 expect(result.length).toEqual(1)47 await expect(provider.verify()).resolves.toBeTruthy()48 })49 // this is the same test as above but the only difference being that it uses50 // the query param to ask for specific movies. this can be used as another step51 // in the workshop but for getting things going easily it is commented to begin with52 test.skip('should receive movie statistics for specified movies', async () => {53 await provider.addInteraction({54 state: 'Has reviews statistics for movie',55 uponReceiving: 'a request for movies stats summary',56 withRequest: {57 method: 'GET',58 path: `/stats`,59 query: {60 'movieId[]': Matchers.eachLike('1')61 }62 },63 willRespondWith: {64 status: 200,65 headers: { 'Content-Type': 'application/json; charset=utf-8' },66 body: [67 {68 'id': Matchers.like('1'),69 'totalReviews': Matchers.like(100),70 'averageRating': Matchers.like(7.5)71 }72 ]73 }74 })75 const result = await ReviewsClient.getMoviesStatistics([1])76 expect(result.length).toEqual(1)77 await expect(provider.verify()).resolves.toBeTruthy()78 })79 test('should successfully receive a request for a movies review summary', async () => {80 await provider.addInteraction({81 state: 'Has a few reviews',82 uponReceiving: 'a request for movie reviews summary',83 withRequest: {84 method: 'GET',85 path: `/reviews`,86 query: {87 'movieId[]': Matchers.eachLike('1')88 }89 },90 willRespondWith: {91 status: 200,92 headers: { 'Content-Type': 'application/json; charset=utf-8' },93 body: Matchers.eachLike(94 {95 'movieId': '1',96 'headline': Matchers.like('a clickbait headline'),97 'message': Matchers.like('hopefully a positive review'),98 'ipAddress': Matchers.ipv4Address(),99 "gender": Matchers.term({100 matcher: 'F|M',101 generate: 'F'102 }),103 'anonymous': Matchers.boolean(),104 'createdAt': Matchers.iso8601DateTimeWithMillis()105 }106 )107 }108 })109 const result = await ReviewsClient.getMoviesReviews([1])110 expect(result.length).toEqual(1)111 await expect(provider.verify()).resolves.toBeTruthy()112 })113 test('should handle a request that responds with no reviews summary', async () => {114 await provider.addInteraction({115 state: 'Has no reviews',116 uponReceiving: 'a request for movies reviews',117 withRequest: {118 method: 'GET',119 path: `/reviews`,120 query: {121 'movieId[]': Matchers.eachLike('1')122 }123 },124 willRespondWith: {125 status: 404126 }127 })128 const result = await ReviewsClient.getMoviesReviews([1])129 expect(result.length).toEqual(0)130 await expect(provider.verify()).resolves.toBeTruthy()131 })132 test('should handle a request that responds with no stats summary', async () => {133 await provider.addInteraction({134 state: 'Has no statistics',135 uponReceiving: 'a request for movies statistics',136 withRequest: {137 method: 'GET',138 path: `/stats`139 },140 willRespondWith: {141 status: 404142 }143 })144 const result = await ReviewsClient.getAllMoviesStatistics()145 expect(result.length).toEqual(0)146 await expect(provider.verify()).resolves.toBeTruthy()147 })148 })...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Matchers } = require('@pact-foundation/pact');2const { somethingLike } = Matchers;3const getSomething = {4 withRequest: {5 query: {6 foo: somethingLike('bar'),7 },8 },9};10module.exports = {11};12const { Matchers } = require('@pact-foundation/pact');13const { somethingLike } = Matchers;14const { getSomething } = require('./test2');15describe('Test 2', () => {16 it('test 2', async () => {17 await provider.addInteraction(getSomething);18 });19});20const { Matchers } = require('@pact-foundation/pact');21const { somethingLike } = Matchers;22const getSomething = {23 withRequest: {24 query: {25 foo: somethingLike('bar'),26 },27 },28};29module.exports = {30};31const { Matchers } = require('@pact-foundation/pact');32const { somethingLike } = Matchers;33const { getSomething } = require('./test1');34describe('Test 1', () => {35 it('test 1', async () => {36 const interaction = {37 withRequest: {38 headers: {39 },40 },41 willRespondWith: {42 headers: {43 'Content-Type': 'application/json; charset=utf-8',44 },45 body: [somethingLike({ id: 1, name: 'todo 1' })],46 },47 };48 await provider.addInteraction(interaction);49 });50});51const { Matchers } = require('@pact-foundation/pact');52const { somethingLike } = Matchers;53const getSomething = {54 withRequest: {

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Pact } = require('@pact-foundation/pact');2const { somethingLike: like } = require('@pact-foundation/pact').Matchers;3const { eachLike: likeEach } = require('@pact-foundation/pact').Matchers;4const { term } = require('@pact-foundation/pact').Matchers;5const { somethingLike: like } = require('@pact-foundation/pact').Matchers;6const path = require('path');7const {

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Matchers } = require("@pact-foundation/pact");2const { like, term, somethingLike, eachLike, iso8601DateTimeWithMillis } = Matchers;3const matcher = {4 id: like(1),5 name: like("John"),6 email: like("

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