Best JavaScript code snippet using pact-foundation-pact
TransactionServiceSpec.js
Source: TransactionServiceSpec.js
1/*****************************************************************************2 * Open MCT, Copyright (c) 2014-2018, United States Government3 * as represented by the Administrator of the National Aeronautics and Space4 * Administration. All rights reserved.5 *6 * Open MCT is licensed under the Apache License, Version 2.0 (the7 * "License"); you may not use this file except in compliance with the License.8 * You may obtain a copy of the License at9 * http://www.apache.org/licenses/LICENSE-2.0.10 *11 * Unless required by applicable law or agreed to in writing, software12 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT13 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the14 * License for the specific language governing permissions and limitations15 * under the License.16 *17 * Open MCT includes source code licensed under additional open source18 * licenses. See the Open Source Licenses file (LICENSES.md) included with19 * this source code distribution or the Licensing information page available20 * at runtime from the About dialog for additional information.21 *****************************************************************************/22/*global define,describe,it,expect,beforeEach,jasmine*/23define(24 ["../../src/services/TransactionService"],25 function (TransactionService) {26 describe("The Transaction Service", function () {27 var mockQ,28 mockLog,29 transactionService;30 function fastPromise(val) {31 return {32 then: function (callback) {33 return fastPromise(callback(val));34 }35 };36 }37 beforeEach(function () {38 mockQ = jasmine.createSpyObj("$q", ["all"]);39 mockQ.all.and.returnValue(fastPromise());40 mockLog = jasmine.createSpyObj("$log", ["error"]);41 transactionService = new TransactionService(mockQ, mockLog);42 });43 it("isActive returns true if a transaction is in progress", function () {44 expect(transactionService.isActive()).toBe(false);45 transactionService.startTransaction();46 expect(transactionService.isActive()).toBe(true);47 });48 it("addToTransaction queues onCommit and onCancel functions", function () {49 var onCommit = jasmine.createSpy('onCommit'),50 onCancel = jasmine.createSpy('onCancel');51 transactionService.startTransaction();52 transactionService.addToTransaction(onCommit, onCancel);53 expect(transactionService.size()).toBe(1);54 });55 it("size function returns size of commit and cancel queues", function () {56 var onCommit = jasmine.createSpy('onCommit'),57 onCancel = jasmine.createSpy('onCancel');58 transactionService.startTransaction();59 transactionService.addToTransaction(onCommit, onCancel);60 transactionService.addToTransaction(onCommit, onCancel);61 transactionService.addToTransaction(onCommit, onCancel);62 expect(transactionService.size()).toBe(3);63 });64 describe("commit", function () {65 var onCommits;66 beforeEach(function () {67 onCommits = [0, 1, 2].map(function (val) {68 return jasmine.createSpy("onCommit" + val);69 });70 transactionService.startTransaction();71 onCommits.forEach(transactionService.addToTransaction.bind(transactionService));72 });73 it("commit calls all queued commit functions", function () {74 expect(transactionService.size()).toBe(3);75 transactionService.commit();76 onCommits.forEach(function (spy) {77 expect(spy).toHaveBeenCalled();78 });79 });80 it("commit resets active state and clears queues", function () {81 transactionService.commit();82 expect(transactionService.isActive()).toBe(false);83 expect(transactionService.size()).toBe(0);84 expect(transactionService.size()).toBe(0);85 });86 });87 describe("cancel", function () {88 var onCancels;89 beforeEach(function () {90 onCancels = [0, 1, 2].map(function (val) {91 return jasmine.createSpy("onCancel" + val);92 });93 transactionService.startTransaction();94 onCancels.forEach(function (onCancel) {95 transactionService.addToTransaction(undefined, onCancel);96 });97 });98 it("cancel calls all queued cancel functions", function () {99 expect(transactionService.size()).toBe(3);100 transactionService.cancel();101 onCancels.forEach(function (spy) {102 expect(spy).toHaveBeenCalled();103 });104 });105 it("cancel resets active state and clears queues", function () {106 transactionService.cancel();107 expect(transactionService.isActive()).toBe(false);108 expect(transactionService.size()).toBe(0);109 });110 });111 });112 }...
transaction.test.js
Source: transaction.test.js
1import jest from 'jest-mock'2import TransactionService from '../services/TransactionService.js'3describe('API tests', () => {4 let transaction5 let account6 let response7 let transactionService8 beforeEach(async () => {9 transactionService = new TransactionService()10 account = {11 idPessoa: 1,12 saldo: 5,13 flagAtivo: true,14 limiteSaqueDiario: 100,15 tipoConta: 216 }17 response = {18 saldoAnterior: 5,19 novoSaldo: 520 }21 transaction = {22 idConta: 1,23 valor: 1024 }25 })26 describe('Transaction endpoints', () => {27 test.each(['deposit', 'withdraw'])('Should %s with valid data', async type => {28 transactionService.accountRepository.accounts.findUnique = jest.fn(() => account)29 transactionService.accountRepository.accounts.update = jest.fn(() => account)30 transactionService.transactionRepository.transactions.create = jest.fn(() => transaction)31 transactionService.transactionRepository.transactions.groupBy = jest.fn(() => 10)32 const data = await transactionService.transaction(transaction, type)33 expect(data).toEqual(response)34 })35 test.each(['deposit', 'withdraw'])('Should %s with invalid data', async type => {36 try {37 transaction.valor = '10'38 await transactionService.transaction(transaction, type)39 } catch (error) {40 expect(error.message).toEqual('ValidationError: valor must be a monetary value')41 }42 })43 test.each([100, 110])('Should throw a daily withdraw limit', async sum => {44 try {45 transactionService.accountRepository.accounts.findUnique = jest.fn(() => account)46 transactionService.accountRepository.accounts.update = jest.fn(() => account)47 transactionService.transactionRepository.transactions.create = jest.fn(() => transaction)48 transactionService.transactionRepository.transactions.groupBy = jest.fn(() => sum)49 await transactionService.transaction(transaction, 'withdraw')50 } catch (error) {51 expect(error.message).toEqual(`Daily withdraw limit ${account.limiteSaqueDiario} has been reached`)52 }53 })54 it('Should throw account not found', async () => {55 try {56 transactionService.accountRepository.accounts.findUnique = jest.fn(() => null)57 await transactionService.transaction(transaction)58 } catch (error) {59 expect(error.message).toEqual('Account not found')60 }61 })62 it('Should throw account is blocked', async () => {63 try {64 account.flagAtivo = false65 transactionService.accountRepository.accounts.findUnique = jest.fn(() => account)66 await transactionService.transaction(transaction)67 } catch (error) {68 expect(error.message).toEqual(`Operation not allowed account ${account.idConta} is blocked`)69 }70 })71 })...
Using AI Code Generation
1const { pactWith } = require('jest-pact');2const { Matchers } = require('@pact-foundation/pact');3const { transactionService } = require('./transactionService');4const { like, eachLike, term } = Matchers;5pactWith({ consumer: 'TransactionService', provider: 'Transaction' }, provider => {6 describe('TransactionService', () => {7 beforeEach(() => provider.setup());8 afterEach(() => provider.verify());9 describe('when a request to get transactions is made', () => {10 beforeEach(() => {11 const interaction = {12 withRequest: {13 headers: {14 'Content-Type': 'application/json;charset=utf-8',15 },16 },17 willRespondWith: {18 headers: {19 'Content-Type': 'application/json;charset=utf-8',20 },21 body: eachLike({22 id: like('1'),23 type: like('transfer'),24 attributes: {25 from: like('John'),26 to: like('Mary'),27 amount: like('100'),28 },29 }),30 },31 };32 return provider.addInteraction(interaction);33 });34 it('returns the correct data', () => {35 return transactionService().then(response => {36 expect(response.data).toEqual([37 {38 attributes: {39 },40 },41 ]);42 });43 });44 });45 });46});47const axios = require('axios');48const { Matchers } = require('@pact-foundation/pact');49const { eachLike, like } = Matchers;50const transactionService = () =>51 return response;52 });53module.exports = {54};55const express = require('express');56const app = express();57app.get('/transactions', (req, res) => {58 res.json([
Using AI Code Generation
1var transactionService = require('pact-foundation-pact-node/src/transactionService');2var path = require('path');3var pactFile = path.resolve(__dirname, 'pacts', 'test.json');4transactionService.verify(pactFile, {5}).then(function (result) {6 console.log('result: ' + result);7}).catch(function (e) {8 console.log('error: ' + e);9});
Using AI Code Generation
1const pact = require('pact-foundation/pact-node');2pact.transactionService({3})4.then(function (res) {5console.log(res);6})7.catch(function (err) {8console.log(err);9});10const pact = require('pact-foundation/pact-node');11pact.mockService({12})13.then(function (res) {14console.log(res);15})16.catch(function (err) {17console.log(err);18});
Check out the latest blogs from LambdaTest on this topic:
Hey everyone! We hope you had a great Hacktober. At LambdaTest, we thrive to bring you the best with each update. Our engineering and tech teams work at lightning speed to deliver you a seamless testing experience.
Having a good web design can empower business and make your brand stand out. According to a survey by Top Design Firms, 50% of users believe that website design is crucial to an organization’s overall brand. Therefore, businesses should prioritize website design to meet customer expectations and build their brand identity. Your website is the face of your business, so it’s important that it’s updated regularly as per the current web design trends.
In today’s world, an organization’s most valuable resource is its customers. However, acquiring new customers in an increasingly competitive marketplace can be challenging while maintaining a strong bond with existing clients. Implementing a customer relationship management (CRM) system will allow your organization to keep track of important customer information. This will enable you to market your services and products to these customers better.
When I started writing tests with Cypress, I was always going to use the user interface to interact and change the application’s state when running tests.
Sometimes, in our test code, we need to handle actions that apparently could not be done automatically. For example, some mouse actions such as context click, double click, drag and drop, mouse movements, and some special key down and key up actions. These specific actions could be crucial depending on the project context.
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!!