How to use EXPECTED_BODY method in pact-foundation-pact

Best JavaScript code snippet using pact-foundation-pact

books.test.js

Source:books.test.js Github

copy

Full Screen

1const request = require("supertest");2const app = require("src/app");3const { conn } = require("src/adapters");4describe("Test Books URLs", () => {5 beforeAll(async () => {6 await conn.sync({ force: true });7 });8 it("Retrive books from empty database", async () => {9 await request(app).get("/api/books").expect(200).expect([]);10 });11 it("Create new book", async () => {12 const body = { title: "new book" };13 const response = await request(app).post("/api/books").send(body);14 const response_body = JSON.parse(response["text"]);15 const response_status = response["status"];16 const response_id = response_body["id"];17 const response_title = response_body["title"];18 expect(response_status).toEqual(201);19 expect(response_id).toEqual(1);20 expect(response_title).toEqual(body["title"]);21 });22 it("Try to create new book with an invalid schema", async () => {23 const body = { invalid_key: "new book" };24 const expected_body = {25 errors: ["title is a required field"],26 inner: [],27 message: "title is a required field",28 name: "ValidationError",29 params: { path: "title" },30 path: "title",31 type: "required",32 value: { invalid_key: "new book" },33 };34 const response = await request(app).post("/api/books").send(body);35 const response_status = response["status"];36 const response_body = JSON.parse(response["text"]);37 expect(response_status).toEqual(400);38 expect(response_body).toEqual(expected_body);39 });40 it("Retrive books from a database with data", async () => {41 const body = { title: "new book 2" };42 const expected_body = [43 { id: 1, title: "new book" },44 { id: 2, title: "new book 2" },45 ];46 await request(app).post("/api/books").send(body);47 const response = await request(app).get("/api/books");48 const response_status = response["status"];49 const response_body = JSON.parse(response["text"]);50 expect(response_status).toEqual(200);51 response_body.map((response_book) => {52 const expected_book = expected_body.find(53 (expected_book) => expected_book["id"] === response_book["id"]54 );55 expect(response_book["id"]).toEqual(expected_book["id"]);56 expect(response_book["title"]).toEqual(expected_book["title"]);57 });58 });59 it("Find book", async () => {60 const expected_body = { id: 2, title: "new book 2" };61 const response = await request(app).get(62 `/api/books/${expected_body["id"]}`63 );64 const response_status = response["status"];65 const response_body = JSON.parse(response["text"]);66 expect(response_status).toEqual(200);67 expect(response_body["id"]).toEqual(expected_body["id"]);68 expect(response_body["title"]).toEqual(expected_body["title"]);69 });70 it("Book not found", async () => {71 const id = 999;72 const response = await request(app).get(`/api/books/${id}`);73 const response_status = response["status"];74 const response_body = JSON.parse(response["text"]);75 expect(response_status).toEqual(404);76 expect(response_body).toEqual(`No se encontro el libro con el id: ${id}`);77 });78 it("Update book", async () => {79 const title = "new book updated";80 const body = { title };81 const expected_body = { id: 1, title };82 const response = await request(app)83 .put(`/api/books/${expected_body["id"]}`)84 .send(body);85 const response_status = response["status"];86 const response_body = JSON.parse(response["text"]);87 expect(response_status).toEqual(200);88 expect(response_body["id"]).toEqual(expected_body["id"]);89 expect(response_body["title"]).toEqual(expected_body["title"]);90 });91 it("Try to update a workbook that does not exist", async () => {92 const title = "new book updated";93 const body = { title };94 const expected_body = { id: 999, title };95 const response = await request(app)96 .put(`/api/books/${expected_body["id"]}`)97 .send(body);98 const response_status = response["status"];99 const response_body = JSON.parse(response["text"]);100 expect(response_status).toEqual(404);101 expect(response_body).toEqual(102 `No se encontro el libro con el id: ${expected_body["id"]}`103 );104 });105 it("Try to update new book with an invalid schema", async () => {106 const body = { invalid_key: "new book" };107 const expected_body = {108 errors: ["title is a required field"],109 inner: [],110 message: "title is a required field",111 name: "ValidationError",112 params: { path: "title" },113 path: "title",114 type: "required",115 value: { invalid_key: "new book" },116 };117 const response = await request(app).put("/api/books/1").send(body);118 const response_status = response["status"];119 const response_body = JSON.parse(response["text"]);120 expect(response_status).toEqual(400);121 expect(response_body).toEqual(expected_body);122 });123 it("Delete book", async () => {124 const id = 1;125 await request(app)126 .delete(`/api/books/${id}`)127 .expect(200)128 .expect(`Libro con id ${id} fue eliminado`);129 });130 it("Try to delete a workbook that does not exist", async () => {131 const id = 999;132 const response = await request(app).delete(`/api/books/${id}`);133 const response_status = response["status"];134 const response_body = JSON.parse(response["text"]);135 expect(response_status).toEqual(404);136 expect(response_body).toEqual(`No se encontro el libro con el id: ${id}`);137 });138 afterAll(async () => {139 await conn.close();140 });...

Full Screen

Full Screen

CepController.spec.ts

Source:CepController.spec.ts Github

copy

Full Screen

1import request from 'supertest';2import server from '../src/server';3describe('CepController', () => {4 afterEach(() => {5 server.close();6 });7 describe('GET /cep/:cep com parametros invalidos', () => {8 test('parametro vazio', async () => {9 const supertest = await request(server).get('/cep/');10 const expected_response = {};11 const expected_status = 404;12 expect(supertest.status).toBe(expected_status);13 expect(supertest.body).toEqual(expected_response);14 });15 test('parametro < 8 digitos numericos', async () => {16 const supertest1 = await request(server).get('/cep/1234567');17 const supertest2 = await request(server).get('/cep/1234-56');18 const supertest3 = await request(server).get('/cep/1testeste');19 const expected_body = {};20 const expected_status = 400;21 expect(supertest1.status).toBe(expected_status);22 expect(supertest1.body).toEqual(expected_body);23 expect(supertest2.status).toBe(expected_status);24 expect(supertest2.body).toEqual(expected_body);25 expect(supertest3.status).toBe(expected_status);26 expect(supertest3.body).toEqual(expected_body);27 });28 test('parametro > 8 digitos numericos', async () => {29 const supertest1 = await request(server).get('/cep/123456789');30 const supertest2 = await request(server).get('/cep/12345-6789');31 const supertest3 = await request(server).get('/cep/123456789testeste');32 const expected_body = {};33 const expected_status = 400;34 expect(supertest1.status).toBe(expected_status);35 expect(supertest1.body).toEqual(expected_body);36 expect(supertest2.status).toBe(expected_status);37 expect(supertest2.body).toEqual(expected_body);38 expect(supertest3.status).toBe(expected_status);39 expect(supertest3.body).toEqual(expected_body);40 });41 });42 describe('GET /cep/:cep com parametros validos', () => {43 test('parametro = 8 digitos numericos e cep invalido', async () => {44 const supertest1 = await request(server).get('/cep/12345678');45 const supertest2 = await request(server).get('/cep/12345-678');46 const supertest3 = await request(server).get('/cep/12345678teste-ste');47 const expected_body = {};48 const expected_status = 406;49 expect(supertest1.status).toBe(expected_status);50 expect(supertest1.body).toEqual(expected_body);51 expect(supertest2.status).toBe(expected_status);52 expect(supertest2.body).toEqual(expected_body);53 expect(supertest3.status).toBe(expected_status);54 expect(supertest3.body).toEqual(expected_body);55 });56 test('parametro = 8 digitos numericos e cep válido', async () => {57 const supertest1 = await request(server).get('/cep/18460001');58 const supertest2 = await request(server).get('/cep/18460-001');59 const supertest3 = await request(server).get('/cep/18460001testes-te');60 const expected_body = {61 cep: '18460-001',62 localidade: 'Itararé',63 logradouro: 'Rua Campos Salles',64 uf: 'SP',65 };66 const expected_status = 200;67 expect(supertest1.status).toBe(expected_status);68 expect(supertest1.body).toEqual(expected_body);69 expect(supertest2.status).toBe(expected_status);70 expect(supertest2.body).toEqual(expected_body);71 expect(supertest3.status).toBe(expected_status);72 expect(supertest3.body).toEqual(expected_body);73 });74 test('parametro = 8 digitos numericos e cep desconhecido', async () => {75 const supertest1 = await request(server).get('/cep/18460000');76 const supertest2 = await request(server).get('/cep/18460-000');77 const supertest3 = await request(server).get('/cep/18460000testes-te');78 const expected_body = {};79 const expected_status = 406;80 expect(supertest1.status).toBe(expected_status);81 expect(supertest1.body).toEqual(expected_body);82 expect(supertest2.status).toBe(expected_status);83 expect(supertest2.body).toEqual(expected_body);84 expect(supertest3.status).toBe(expected_status);85 expect(supertest3.body).toEqual(expected_body);86 });87 });...

Full Screen

Full Screen

mnisa-app.spec.js

Source:mnisa-app.spec.js Github

copy

Full Screen

1/* eslint-disable jest/valid-expect-in-promise */2// This is the Pact test for the mnisa app3const { pactWith } = require("jest-pact");4const { Matchers } = require("@pact-foundation/pact");5const { like, eachLike, regex } = Matchers;6// Load the consumer client code which we will call in our test7const { addTask, listTasks } = require("../mnisa-app.js");8const sampleTask = {9 id: 1,10 user_id: 1,11 name: "A Task",12};13pactWith(14 { consumer: "mnisa app", provider: "mnisa api", port: 1234, timeout: 50000 },15 (provider) => {16 // This is the body we expect to get back from the provider17 // const EXPECTED_BODY = {18 // id: 1,19 // user_id: like(sampleTask.user_id),20 // name: regex({21 // matcher: "^[A-Za-z0-9& ,.!_]+$",22 // generate: sampleTask.name,23 // }),24 // };25 const EXPECTED_BODY = {26 id: 1,27 user_id: 1,28 name: 'A Task',29 };30 describe("get task", () => {31 beforeEach(() => {32 // First we setup the expected interactions that should occur during the test33 const interaction = {34 state: "i have a list of tasks",35 uponReceiving: "a request for all tasks by user id",36 withRequest: {37 method: "GET",38 path: "/api/task",39 query: "userId=1",40 headers: {41 Accept: "application/json",42 "Access-Control-Allow-Origin": "*",43 },44 },45 willRespondWith: {46 status: 200,47 headers: {48 "Content-Type": "application/json",49 },50 body: eachLike(EXPECTED_BODY),51 },52 };53 return provider.addInteraction(interaction);54 });55 it("returns the correct response", () => {56 // We call our consumer code, and that will make requests to the mock server57 listTasks(provider.mockService.baseUrl).then((response) => {58 expect(response.data).toEqual([EXPECTED_BODY]);59 // expect(Array.isArray(response.data)).toBe(true);60 // expect(response.data[0].id).toBe(1);61 });62 });63 });64 // describe("add task", () => {65 // const EXPECTED_BODY = {66 // message: {67 // id: 1,68 // user_id: 1,69 // name: "New Task",70 // },71 // };72 // beforeEach(() => {73 // // First we setup the expected interactions that should occur during the test74 // const interaction = {75 // state: "i have a task to add",76 // uponReceiving: "a request for adding task",77 // withRequest: {78 // method: "POST",79 // path: "/api/task",80 // body: {81 // userId: 1,82 // name: "New Task",83 // },84 // headers: {85 // Accept: "application/json",86 // "Access-Control-Allow-Origin": "*",87 // },88 // },89 // willRespondWith: {90 // status: 200,91 // headers: {92 // "Content-Type": "application/json",93 // },94 // body: EXPECTED_BODY,95 // },96 // };97 // return provider.addInteraction(interaction);98 // });99 // it("add task and return created task", () => {100 // // We call our consumer code, and that will make requests to the mock server101 // addTask(provider.mockService.baseUrl).then((response) => {102 // return expect(response.data).toEqual(EXPECTED_BODY);103 // });104 // });105 // });106 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var pact = require('pact-foundation/pact-node');2var path = require('path');3var opts = {4 pactUrls: [path.resolve(process.cwd(), 'pacts', 'test1-test2.json')]5};6pact.verifyPacts(opts)7 .then(function() {8 console.log("Pact Verification Complete!");9 console.log("");10 })11 .catch(function(e) {12 console.log(e);13 });14var pact = require('pact-foundation/pact-node');15var path = require('path');16var opts = {17 pactUrls: [path.resolve(process.cwd(), 'pacts', 'test1-test2.json')]18};19pact.verifyPacts(opts)20 .then(function() {21 console.log("Pact Verification Complete!");22 console.log("");23 })24 .catch(function(e) {25 console.log(e);26 });

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Matchers } = require('@pact-foundation/pact');2const expectedBody = {3 "name": Matchers.somethingLike("John"),4 "age": Matchers.somethingLike(20)5};6module.exports = expectedBody;7const { Matchers } = require('@pact-foundation/pact');8const expectedBody = {9 "name": Matchers.somethingLike("John"),10 "age": Matchers.somethingLike(20)11};12module.exports = expectedBody;13at tryCatcher (/Users/abc/Documents/abc/node_modules/bluebird/js/release/util.js:16:23)14at Promise._settlePromiseFromHandler (/Users/abc/Documents/abc/node_modules/bluebird/js/release/promise.js:547:31)15at Promise._settlePromise (/Users/abc/Documents/abc/node_modules/bluebird/js/release/promise.js:604:18)16at Promise._settlePromise0 (/Users/abc/Documents/abc/node_modules/bluebird/js/release/promise.js:649:10)17at Promise._settlePromises (/Users/abc/Documents/abc/node_modules/bluebird/js/release/promise.js:729:18)18at _drainQueueStep (/Users/abc/Documents/abc/node_modules/bluebird/js/release/async.js:93:12)19at _drainQueue (/Users/abc/Documents/abc/node_modules/bluebird/js/release/async.js:86:9)20at Async._drainQueues (/Users/abc/Documents/abc/node_modules/bluebird/js/release/async.js:102:5)21at Immediate.Async.drainQueues (/Users/abc/Documents/abc/node_modules/bluebird/js/release/async.js:15:14)22at processImmediate (internal/timers.js:456:21)

Full Screen

Using AI Code Generation

copy

Full Screen

1const path = require('path');2const { Verifier } = require('@pact-foundation/pact');3const chai = require('chai');4const chaiAsPromised = require('chai-as-promised');5chai.use(chaiAsPromised);6const expect = chai.expect;7describe("Pact Verification", () => {8 it("should validate the expectations of Test2", () => {9 const opts = {10 pactUrls: [path.resolve(process.cwd(), "pacts", "test2-test1.json")],11 log: path.resolve(process.cwd(), "logs", "pact.log"),12 stateHandlers: {13 "test GET": () => {14 return new Promise((resolve, reject) => {15 resolve();16 });17 },18 },19 };20 return new Verifier(opts)21 .verifyProvider()22 .then((output) => {23 console.log("Pact Verification Complete!");24 console.log(output);25 });26 });27});28const chai = require('chai');29const chaiAsPromised = require('chai-as-promised');30const chaiSubset = require('chai-subset');31const chaiJsonSchema = require('chai-json-schema');32const chaiJsonEqual = require('chai-json-equal');33const chaiJsonPattern = require('chai-json-pattern').default;34const chaiJsonSchemaAjv = require('chai-json-schema-ajv');

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