How to use suggestedMates method in pact-foundation-pact

Best JavaScript code snippet using pact-foundation-pact

consumer.test.js

Source:consumer.test.js Github

copy

Full Screen

1const path = require("path")2const chai = require("chai")3const chaiAsPromised = require("chai-as-promised")4chai.use(chaiAsPromised)5const expect = chai.expect6const { Pact, Matchers } = require("@pact-foundation/pact")7const LOG_LEVEL = process.env.LOG_LEVEL || "WARN"8const request = require("superagent")9const getApiEndpoint = () => process.env.API_HOST || "http://localhost:8081"10const authHeader = { Authorization: "Bearer token", }11describe("Pact", () => {12 const provider = new Pact({13 consumer: "Matching Service",14 provider: "Animal Profile Service",15 port: 3000, // You can set the port explicitly here or dynamically (see setup() below)16 log: path.resolve(process.cwd(), "logs", "mockserver-integration.log"),17 dir: path.resolve(process.cwd(), "pacts"),18 logLevel: LOG_LEVEL,19 spec: 2,20 })21 // Alias flexible matchers for simplicity22 const { eachLike, like, term, iso8601DateTimeWithMillis } = Matchers23 const MIN_ANIMALS = 224 // Define animal payload, with flexible matchers25 //26 // This makes the test much more resilient to changes in actual data.27 // Here we specify the 'shape' of the object that we care about.28 // It is also import here to not put in expectations for parts of the29 // API we don't care about30 const animalBodyExpectation = {31 id: like(1),32 available_from: iso8601DateTimeWithMillis(),33 first_name: like("Billy"),34 last_name: like("Goat"),35 animal: like("goat"),36 age: like(21),37 gender: term({38 matcher: "F|M",39 generate: "M",40 }),41 location: {42 description: like("Melbourne Zoo"),43 country: like("Australia"),44 post_code: like(3000),45 },46 eligibility: {47 available: like(true),48 previously_married: like(false),49 },50 interests: eachLike("walks in the garden/meadow"),51 }52 // Define animal list payload, reusing existing object matcher53 const animalListExpectation = eachLike(animalBodyExpectation, { min: MIN_ANIMALS, })54 // const animalListExpectation = animalBodyExpectation55 // Setup a Mock Server before unit tests run.56 // This server acts as a Test Double for the real Provider API.57 // We then call addInteraction() for each test to configure the Mock Service58 // to act like the Provider59 // It also sets up expectations for what requests are to come, and will fail60 // if the calls are not seen.61 before(() => {62 return provider.setup().then(opts => {63 // Get a dynamic port from the runtime64 process.env.API_HOST = `http://localhost:${opts.port}`65 })66 })67 // After each individual test (one or more interactions)68 // we validate that the correct request came through.69 // This ensures what we _expect_ from the provider, is actually70 // what we've asked for (and is what gets captured in the contract)71 afterEach(() => provider.verify())72 // Configure and import consumer API73 // Note that we update the API endpoint to point at the Mock Service74 // const {75 // createMateForDates,76 // suggestion,77 // getAnimalById,78 // } = require("./consumer")79 const availableAnimals = () => {80 return request81 .get(`${getApiEndpoint()}/animals/available`)82 .set(authHeader)83 .then(res => res.body)84 }85 const getAnimalById = id => {86 return request87 .get(`${getApiEndpoint()}/animals/${id}`)88 .set(authHeader)89 .then(res => res.body, () => null)90 }91 // Verify service client works as expected.92 // Note that we don't call the consumer API endpoints directly, but93 // use unit-style tests that test the collaborating function behaviour -94 // we want to test the function that is calling the external service.95 describe("when a call to list all animals from the Animal Service is made", () => {96 describe("and the user is not authenticated", () => {97 before(() =>98 provider.addInteraction({99 state: "is not authenticated",100 uponReceiving: "a request for all animals",101 withRequest: {102 method: "GET",103 path: "/animals/available",104 },105 willRespondWith: {106 status: 401,107 },108 })109 )110 it("returns a 401 unauthorized", async () => {111 // console.log()112 // suggestion(suitor).then(o=>{113 // console.log('hello')114 // }).catch(err=> console.log('i am here'+ err))115 // return expect(suggestion(suitor)).to.eventually.be.rejectedWith("Unauthorized")116 return expect((availableAnimals())).to.eventually.be.rejectedWith("Unauthorized")117 // availableAnimals().then(a => console.log).catch(err => console.log('hello ' + err))118 })119 })120 describe("and the user is authenticated", () => {121 describe("and there are animals in the database", () => {122 before(() =>123 provider.addInteraction({124 state: "Has some animals",125 uponReceiving: "a request for all animals",126 withRequest: {127 method: "GET",128 path: "/animals/available",129 headers: { Authorization: "Bearer token" },130 },131 willRespondWith: {132 status: 200,133 headers: {134 "Content-Type": "application/json; charset=utf-8",135 },136 body: animalListExpectation,137 },138 })139 )140 it("returns a list of animals", done => {141 // const suggestedMates = suggestion(suitor)142 const suggestedMates = availableAnimals();143 availableAnimals().then(a => {144 // console.log(a)145 expect(a.length).to.not.equal(9);146 done();147 })148 // expect(suggestedMates).to.eventually.have.deep.property("id", 11)149 // expect(suggestedMates).to.eventually.have.nested.property(150 // "suggestions[0].score",151 // 95152 // )153 // expect(suggestedMates)154 // // .to.eventually.have.property("suggestions")155 // .notify(done)156 })157 })158 })159 })160 describe("when a call to the Animal Service is made to retreive a single animal by ID", () => {161 describe("and there is an animal in the DB with ID 1", () => {162 before(() =>163 provider.addInteraction({164 state: "Has an animal with ID 1",165 uponReceiving: "a request for an animal with ID 1",166 withRequest: {167 method: "GET",168 path: term({ generate: "/animals/1", matcher: "/animals/[0-9]+" }),169 // path: "/animals/11",170 headers: { Authorization: "Bearer token" },171 },172 willRespondWith: {173 status: 200,174 headers: {175 "Content-Type": "application/json; charset=utf-8",176 },177 body: animalBodyExpectation,178 },179 })180 )181 it("returns the animal", done => {182 const suggestedMates = getAnimalById(1)183 expect(suggestedMates)184 .to.eventually.have.deep.property("id", 1)185 .notify(done)186 })187 })188 describe("and there no animals in the database", () => {189 before(() =>190 provider.addInteraction({191 state: "Has no animals",192 uponReceiving: "a request for an animal with ID 100",193 withRequest: {194 method: "GET",195 // path: "/animals/100",196 path: term({ generate: "/animals/1", matcher: "/animals/[0-9]+" }),197 headers: { Authorization: "Bearer token" },198 },199 willRespondWith: {200 status: 404,201 },202 })203 )204 it("returns a 404", done => {205 // uncomment below to test a failed verify206 const suggestedMates = getAnimalById(123)207 // const suggestedMates = getAnimalById(100)208 expect(suggestedMates)209 .to.eventually.be.a("null")210 .notify(done)211 })212 })213 })214 // describe("when a call to the Animal Service is made to create a new mate", () => {215 // before(() =>216 // provider.addInteraction({217 // uponReceiving: "a request to create a new mate",218 // withRequest: {219 // method: "POST",220 // path: "/animals",221 // body: like(suitor),222 // headers: {223 // "Content-Type": "application/json; charset=utf-8",224 // },225 // },226 // willRespondWith: {227 // status: 200,228 // headers: {229 // "Content-Type": "application/json; charset=utf-8",230 // },231 // body: like(suitor),232 // },233 // })234 // )235 // it("creates a new mate", done => {236 // expect(createMateForDates(suitor)).to.eventually.be.fulfilled.notify(done)237 // })238 // })239 // Write pact files240 after(() => {241 return provider.finalize()242 })...

Full Screen

Full Screen

consumerCep.spec.js

Source:consumerCep.spec.js Github

copy

Full Screen

1const path = require("path");2const chai = require("chai");3const chaiAsPromised = require("chai-as-promised");4const expect = chai.expect;5const { Pact, Matchers } = require("@pact-foundation/pact");6const LOG_LEVEL = process.env.LOG_LEVEL || "WARN";7chai.use(chaiAsPromised);8describe("Pact", () => {9 const provider = new Pact({10 consumer: "Matching Service",11 provider: "ViaCep Service",12 // port: 1234, // You can set the port explicitly here or dynamically (see setup() below)13 log: path.resolve(process.cwd(), "logs", "mockserver-integration.log"),14 dir: path.resolve(process.cwd(), "pacts"),15 logLevel: LOG_LEVEL,16 spec: 2,17 });18 // Alias flexible matchers for simplicity19 const { eachLike, like, term, iso8601DateTimeWithMillis } = Matchers;20 // Address we want to match :)21 const suitor = {22 id: 1,23 cep: "14808-560",24 logradouro: "Rua Professor Doutor Edmundo Juarez",25 complemento: "",26 bairro: "Jardim Residencial Iedda",27 localidade: "Araraquara",28 uf: "SP",29 ibge: "3503208",30 gia: "1818",31 ddd: "16",32 siafi: "6163",33 };34 const MIN_ADDRESS = 2;35 const cepBodyExpectation = {36 id: like(1),37 cep: like("14808-560"),38 logradouro: like("Rua Professor Doutor Edmundo Juarez"),39 complemento: like(""),40 bairro: like("Jardim Residencial Iedda"),41 localidade: like("Araraquara"),42 uf: like("SP"),43 ibge: like("3503208"),44 gia: like("1818"),45 ddd: like("16"),46 siafi: like("6163"),47 };48 // Define Address list payload, reusing existing object matcher49 const cepListExpectation = eachLike(cepBodyExpectation, {50 min: MIN_ADDRESS,51 });52 // Setup a Mock Server before unit tests run.53 // This server acts as a Test Double for the real Provider API.54 // We then call addInteraction() for each test to configure the Mock Service55 // to act like the Provider56 // It also sets up expectations for what requests are to come, and will fail57 // if the calls are not seen.58 before(() =>59 provider.setup().then((opts) => {60 // Get a dynamic port from the runtime61 process.env.API_HOST = `http://localhost:${opts.port}`;62 })63 );64 // After each individual test (one or more interactions)65 // we validate that the correct request came through.66 // This ensures what we _expect_ from the provider, is actually67 // what we've asked for (and is what gets captured in the contract)68 afterEach(() => provider.verify());69 // Configure and import consumer API70 // Note that we update the API endpoint to point at the Mock Service71 const {72 createMateForDates,73 suggestion,74 getCepById,75 } = require("../consumerCep");76 // Verify service client works as expected.77 //78 // Note that we don't call the consumer API endpoints directly, but79 // use unit-style tests that test the collaborating function behaviour -80 // we want to test the function that is calling the external service.81 describe("when a call to list all address from the Address Service is made", () => {82 describe("and the user is authenticated", () => {83 describe("and there are address in the database", () => {84 before(() =>85 provider.addInteraction({86 state: "Has some address",87 uponReceiving: "a request for all address",88 withRequest: {89 method: "GET",90 path: "/ws/14808560",91 },92 willRespondWith: {93 status: 200,94 headers: {95 "Content-Type": "application/json; charset=utf-8",96 },97 body: cepListExpectation,98 },99 })100 );101 it("returns a list of address", (done) => {102 const suggestedMates = suggestion(suitor);103 expect(suggestedMates).to.eventually.have.deep.property(104 "suggestions[0].score",105 94106 );107 expect(suggestedMates)108 .to.eventually.have.property("suggestions")109 .with.lengthOf(MIN_ADDRESS)110 .notify(done);111 });112 });113 });114 });115 describe("when a call to the Address Service is made to retreive a single address by ID", () => {116 describe("and there is an address in the DB with ID 1", () => {117 before(() =>118 provider.addInteraction({119 state: "Has an address with ID 1",120 uponReceiving: "a request for an address with ID 1",121 withRequest: {122 method: "GET",123 path: term({ generate: "/ws/1", matcher: "/ws/[0-9]+" }),124 },125 willRespondWith: {126 status: 200,127 headers: {128 "Content-Type": "application/json; charset=utf-8",129 },130 body: cepBodyExpectation,131 },132 })133 );134 it("returns the address", (done) => {135 const suggestedMates = getCepById(11);136 expect(suggestedMates)137 .to.eventually.have.deep.property("id", 1)138 .notify(done);139 });140 });141 describe("and there no address in the database", () => {142 before(() =>143 provider.addInteraction({144 state: "Has no address",145 uponReceiving: "a request for an address with ID 100",146 withRequest: {147 method: "GET",148 path: "/ws/100",149 },150 willRespondWith: {151 status: 404,152 },153 })154 );155 it("returns a 404", (done) => {156 // uncomment below to test a failed verify157 // const suggestedMates = getCepById(123)158 const suggestedMates = getCepById(100);159 expect(suggestedMates).to.eventually.be.a("null").notify(done);160 });161 });162 });163 describe("when a call to the Address Service is made to create a new mate", () => {164 before(() =>165 provider.addInteraction({166 uponReceiving: "a request to create a new mate",167 withRequest: {168 method: "POST",169 path: "/ws",170 body: like(suitor),171 headers: {172 "Content-Type": "application/json; charset=utf-8",173 },174 },175 willRespondWith: {176 status: 200,177 headers: {178 "Content-Type": "application/json; charset=utf-8",179 },180 body: like(suitor),181 },182 })183 );184 it("creates a new mate", (done) => {185 expect(createMateForDates(suitor)).to.eventually.be.fulfilled.notify(186 done187 );188 });189 });190 // Write pact files191 after(() => {192 return provider.finalize();193 });...

Full Screen

Full Screen

consumer.spec.js

Source:consumer.spec.js Github

copy

Full Screen

1const path = require('path')2const chai = require('chai')3const chaiAsPromised = require('chai-as-promised')4const expect = chai.expect5const pact = require('../../../src/pact.js')6const MOCK_SERVER_PORT = 12347const LOG_LEVEL = process.env.LOG_LEVEL || 'WARN'8chai.use(chaiAsPromised)9describe('Pact', () => {10 const provider = pact({11 consumer: 'Matching Service',12 provider: 'Animal Profile Service',13 port: MOCK_SERVER_PORT,14 log: path.resolve(process.cwd(), 'logs', 'mockserver-integration.log'),15 dir: path.resolve(process.cwd(), 'pacts'),16 logLevel: LOG_LEVEL,17 spec: 218 })19 // Alias flexible matchers for simplicity20 const { somethingLike: like, term, eachLike } = pact.Matchers21 // Animal we want to match :)22 const suitor = {23 'id': 2,24 'first_name': 'Nanny',25 'animal': 'goat',26 'last_name': 'Doe',27 'age': 27,28 'gender': 'F',29 'location': {30 'description': 'Werribee Zoo',31 'country': 'Australia',32 'post_code': 300033 },34 'eligibility': {35 'available': true,36 'previously_married': true37 },38 'interests': [39 'walks in the garden/meadow',40 'parkour'41 ]42 }43 const MIN_ANIMALS = 244 // Define animal payload, with flexible matchers45 //46 // This makes the test much more resilient to changes in actual data.47 // Here we specify the 'shape' of the object that we care about.48 // It is also import here to not put in expectations for parts of the49 // API we don't care about50 const animalBodyExpectation = {51 'id': like(1),52 'first_name': like('Billy'),53 'last_name': like('Goat'),54 'animal': like('goat'),55 'age': like(21),56 'gender': term({57 matcher: 'F|M',58 generate: 'M'59 }),60 'location': {61 'description': like('Melbourne Zoo'),62 'country': like('Australia'),63 'post_code': like(3000)64 },65 'eligibility': {66 'available': like(true),67 'previously_married': like(false)68 },69 'interests': eachLike('walks in the garden/meadow')70 }71 // Define animal list payload, reusing existing object matcher72 const animalListExpectation = eachLike(animalBodyExpectation, {73 min: MIN_ANIMALS74 })75 // Setup a Mock Server before unit tests run.76 // This server acts as a Test Double for the real Provider API.77 // We call addInteraction() to configure the Mock Service to act like the Provider78 // It also sets up expectations for what requests are to come, and will fail79 // if the calls are not seen.80 before(() => {81 return provider.setup()82 .then(() => {83 provider.addInteraction({84 state: 'Has some animals',85 uponReceiving: 'a request for all animals',86 withRequest: {87 method: 'GET',88 path: '/animals/available'89 },90 willRespondWith: {91 status: 200,92 headers: {93 'Content-Type': 'application/json; charset=utf-8'94 },95 body: animalListExpectation96 }97 })98 })99 .then(() => {100 provider.addInteraction({101 state: 'Has no animals',102 uponReceiving: 'a request for an animal with ID 100',103 withRequest: {104 method: 'GET',105 path: '/animals/100'106 },107 willRespondWith: {108 status: 404109 }110 })111 })112 .then(() => {113 provider.addInteraction({114 state: 'Has an animal with ID 1',115 uponReceiving: 'a request for an animal with ID 1',116 withRequest: {117 method: 'GET',118 path: '/animals/1'119 },120 willRespondWith: {121 status: 200,122 headers: {123 'Content-Type': 'application/json; charset=utf-8'124 },125 body: animalBodyExpectation126 }127 })128 })129 .catch(e => {130 throw new Error("Unable to start the Pact Server: " + e)131 })132 })133 // Configure and import consumer API134 // Note that we update the API endpoint to point at the Mock Service135 process.env.API_HOST = `http://localhost:${MOCK_SERVER_PORT}`136 const {137 suggestion,138 getAnimalById139 } = require('../consumer')140 // Verify service client works as expected.141 //142 // Note that we don't call the consumer API endpoints directly, but143 // use unit-style tests that test the collaborating function behaviour -144 // we want to test the function that is calling the external service.145 describe('when a call to list all animals from the Animal Service is made', () => {146 describe('and there are animals in the database', () => {147 it('returns a list of animals', done => {148 const suggestedMates = suggestion(suitor)149 expect(suggestedMates).to.eventually.have.deep.property('suggestions[0].score', 94)150 expect(suggestedMates).to.eventually.have.property('suggestions').with.lengthOf(MIN_ANIMALS).notify(done)151 })152 })153 })154 describe('when a call to the Animal Service is made to retreive a single animal by ID', () => {155 describe('and there is an animal in the DB with ID 1', () => {156 it('returns the animal', done => {157 const suggestedMates = getAnimalById(1)158 expect(suggestedMates).to.eventually.have.deep.property('id', 1).notify(done)159 })160 })161 describe('and there no animals in the database', () => {162 it('returns a 404', done => {163 // uncomment below to test a failed verify164 // const suggestedMates = getAnimalById(123)165 const suggestedMates = getAnimalById(100)166 expect(suggestedMates).to.eventually.be.a('null').notify(done)167 })168 })169 })170 describe('when interacting with Animal Service', () => {171 it('should validate the interactions and create a contract', () => {172 return provider.verify()173 })174 })175 // Write pact files176 after(() => {177 return provider.finalize()178 })...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var pact = require('pact-foundation/pact-js');2var path = require('path');3var opts = {4 pactUrls: [path.resolve(process.cwd(), 'pacts/test1-test2.json')],5};6pact.verifyPacts(opts).then(function() {7 console.log('success');8}, function(e) {9 console.log('error', e);10});11error { [Error: Error: Pact verification failed!]12' }

Full Screen

Using AI Code Generation

copy

Full Screen

1var Pact = require('pact-foundation-pact');2var request = require('request');3var genes = process.argv[2];4var species = process.argv[3];5var numMates = process.argv[4];6var pact = new Pact();7pact.suggestedMates(genes, species, numMates, function(err, data) {8 if (err) {9 console.log(err);10 } else {11 console.log(JSON.stringify(data));12 }13});

Full Screen

Using AI Code Generation

copy

Full Screen

1var PACT = require('pact-foundation-pact');2var address = process.argv[2];3pact.suggestedMates(address).then(function (response) {4 console.log(response);5});6var PACT = require('pact-foundation-pact');7var address = process.argv[2];8pact.suggestedMates(address).then(function (response) {9 console.log(response);10});

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