Giter VIP home page Giter VIP logo

jest-pact's Introduction

Jest-Pact

npm version npm TravisCI Maintainability Coverage Status Dependency Status devDependency Status

Jest Adaptor to help write Pact files with ease

Features

  • instantiates the PactOptions for you
  • Setups Pact mock service before and after hooks so you don’t have to
  • Set Jest timeout to 30 seconds preventing brittle tests in slow environments like Docker
  • Sensible defaults for the pact options that make sense with Jest
  • Supports both the main release of pact-js (9.x.x) and the beta 10.x.x for Pact spec V3

Jest-Pact Roadmap

  • Ensure that jest-pact plays well with jest's default of watch-mode (This has been mothballed, please see this draft pr for details. Contributions welcome!
  • Ensure that pact failures print nice diffs (at the moment you have to go digging in the log files)
  • Add a setup hook for clearing out log and pact files

Adapter Installation

npm install --save-dev jest-pact
yarn add jest-pact --dev

If you have more than one file with pact tests for the same consumer/provider pair, you will also need to add --runInBand to your jest or react-scripts test command in your package.json. This avoids race conditions with the mock server writing to the pact file.

Usage - Pact-JS V2

Say that your API layer looks something like this:

import axios from 'axios';

const defaultBaseUrl = 'http://your-api.example.com';

export const api = (baseUrl = defaultBaseUrl) => ({
  getHealth: () =>
    axios.get(`${baseUrl}/health`).then((response) => response.data.status),
  /* other endpoints here */
});

Then your test might look like:

import { pactWith } from 'jest-pact';
import { Matchers } from '@pact-foundation/pact';
import api from 'yourCode';

pactWith({ consumer: 'MyConsumer', provider: 'MyProvider' }, provider => {
  let client;

  beforeEach(() => {
    client = api(provider.mockService.baseUrl)
  });

  describe('health endpoint', () => {
    // Here we set up the interaction that the Pact
    // mock provider will expect.
    //
    // jest-pact takes care of validating and tearing
    // down the provider for you.
    beforeEach(() => // note the implicit return.
                     // addInteraction returns a promise.
                     // If you don't want to implicitly return,
                     // you will need to `await` the result
      provider.addInteraction({
        state: "Server is healthy",
        uponReceiving: 'A request for API health',
        willRespondWith: {
          status: 200,
          body: {
            status: Matchers.like('up'),
          },
        },
        withRequest: {
          method: 'GET',
          path: '/health',
        },
      })
    );

    // You also test that the API returns the correct
    // response to the data layer.
    //
    // Although Pact will ensure that the provider
    // returned the expected object, you need to test that
    // your code receives the right object.
    //
    // This is often the same as the object that was
    // in the network response, but (as illustrated
    // here) not always.
    it('returns server health', () => // implicit return again
      client.getHealth().then(health => {
        expect(health).toEqual('up');
      }));
  });
});

Usage - Pact-JS V3

We also include a wrapper for Pact-JS V3.

Note: The API is NOT finalised. Feedback welcome

If you have thoughts or feedback about the DSL, please let us know via slack or open issue.

Currently, only a default for the pact directory is provided by the jest-pact wrapper jest-pact/dist/v3.

import { pactWith } from 'jest-pact/dist/v3';
import { MatchersV3 } from '@pact-foundation/pact';
import api from 'yourCode';

pactWith({ consumer: 'MyConsumer', provider: 'MyProvider' }, (interaction) => {
  interaction('A request for API health', ({ provider, execute }) => {
    beforeEach(() =>
      provider
        .given('Server is healthy')
        .uponReceiving('A request for API health')
        .withRequest({
          method: 'GET',
          path: '/health',
        })
        .willRespondWith({
          status: 200,
          body: {
            status: MatchersV3.like('up'),
          },
        })
    );

    execute('some api call', (mockserver) =>
      api(mockserver.url)
        .health()
        .then((health) => {
          expect(health).toEqual('up');
        })
    );
  });
});

Best practices

You can make your tests easier to read by extracting your request and responses:

/* pact.fixtures.js */
import { Matchers } from '@pact-foundation/pact';

export const healthRequest = {
  uponReceiving: 'A request for API health',
  withRequest: {
    method: 'GET',
    path: '/health',
  },
};

export const healthyResponse = {
  status: 200,
  body: {
    status: Matchers.like('up'),
  },
};
import { pactWith } from 'jest-pact';
import { healthRequest, healthyResponse } from "./pact.fixtures";

import api from 'yourCode';

pactWith({ consumer: 'MyConsumer', provider: 'MyProvider' }, provider => {
  let client;

  beforeEach(() => {
    client = api(provider.mockService.baseUrl)
  });

  describe('health endpoint', () => {

    beforeEach(() =>
      provider.addInteraction({
        state: "Server is healthy",
        ...healthRequest,
        willRespondWith: healthyResponse
      })
    );

    it('returns server health', () =>
      client.getHealth().then(health => {
        expect(health).toEqual('up');
      }));
  });

Common gotchas

  • Forgetting to wait for the promise from addInteraction in beforeEach. You can return the promise, or use async/await. If you forget this, your interaction may not be set up before the test runs.
  • Forgetting to wait for the promise of your API call in it. You can return the promise, or use async/await. If you forget this, your test may pass before the expect assertion runs, causing a potentially false success.
  • Not running jest with --runInBand. If you have multiple test files that write to the same contract, you will need this to avoid intermittent failures when writing the contract file.
  • It's a good idea to specify a different log file for each invocation of pactWith, otherwise the logs will get overwritten when other specs start. If you provide an explicit port, then the default mockserver log filename includes the port number.

API Documentation

Jest-Pact has two primary functions:

  • pactWith(JestPactOptions, (providerMock) => { /* tests go here */ }): a wrapper that sets up a pact mock provider, applies sensible default options, and applies the setup and verification hooks so you don't have to
  • messagePactWith(JestMessageConsumerOptions, (messagePact) => { /* tests go here */ }): a wrapper that sets up a message pact instance and applies sensible default options

Additionally, pactWith.only / fpactWith, pactWith.skip / xpactWith, messagePactWith.only / fmessagePactWith and messagePactWith.skip / xmessagePactWith behave as you would expect from Jest.

There are two types exported:

  • JestProvidedPactFn: This is the type of the second argument to pactWith, ie: (provider: Pact) => void
  • JestPactOptions: An extended version of PactOptions that has some additional convienience options (see below).

Configuration

You can use all the usual PactOptions from pact-js, plus a timeout for telling jest to wait a bit longer for pact to start and run.

pactWith(JestPactOptions, (provider) => {
  // regular http pact tests go here
});
messagePactWith(JestMessageConsumerOptions, (messagePact) => {
  // regular message pact tests go here
});

interface ExtraOptions {
  timeout?: number; // Timeout for pact service start/teardown, expressed in milliseconds
  // Default is 30000 milliseconds (30 seconds).
  logDir?: string; // path for the log file
  logFileName?: string; // filename for the log file
}

type JestPactOptions = PactOptions & ExtraOptions;

type JestMessageConsumerOptions = MessageConsumerOptions & ExtraOptions;

Defaults

Jest-Pact sets some helpful default PactOptions for you. You can override any of these by explicitly setting corresponding option. Here are the defaults:

  • log is set so that log files are written to /pact/logs, and named <consumer>-<provider>-mockserver-interaction.log. If you provided an explicit port, then the log file name is <consumer>-<provider>-mockserver-interaction-port-<portNumber>.log
  • dir is set so that pact files are written to /pact/pacts
  • logLevel is set to warn
  • timeout is 30,000 milliseconds (30 seconds)
  • pactfileWriteMode is set to "update"

Most of the time you won't need to change these.

A common use case for log is to change only the filename or the path for logging. To help with this, Jest-Pact provides convenience options logDir and logFileName. These allow you to set the path or the filename independently. In case you're wondering, if you specify log, logDir and logFileName, the convenience options are ignored and log takes precedence.

Jest Watch Mode

By default Jest will watch all your files for changes, which means it will run in an infinite loop as your pact tests will generate json pact files and log files.

You can get around this by using the following watchPathIgnorePatterns: ["pact/logs/*","pact/pacts/*"] in your jest.config.js

Example

module.exports = {
  testMatch: ['**/*.test.(ts|js)', '**/*.it.(ts|js)', '**/*.pacttest.(ts|js)'],
  watchPathIgnorePatterns: ['pact/logs/*', 'pact/pacts/*'],
};

You can now run your tests with jest --watch and when you change a pact file, or your source code, your pact tests will run

Examples of usage of jest-pact

See Jest-Pact-Typescript which showcases a full consumer workflow written in Typescript with Jest, using this adaptor

  • Example pact tests
    • AWS v4 Signed API Gateway Provider
    • Soap API provider
    • File upload API provider
    • JSON API provider

Examples Installation

  • clone repository [email protected]:YOU54F/jest-pact-typescript.git
  • Run yarn install
  • Run yarn run pact-test

Generated pacts will be output in pact/pacts Log files will be output in pact/logs

Credits

jest-pact's People

Contributors

dependabot[bot] avatar dmhalejr avatar edouard-lopez avatar jamesmbourne avatar joshuajaco avatar ltsuda avatar lucasmoreiradev avatar mefellows avatar pezholio avatar renovate-bot avatar renovate[bot] avatar sonallux avatar timothyjones avatar you54f avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

jest-pact's Issues

jest-pact depends on Jasmine

I'm attempting to upgrade our repo to use jest-circus, but when I do so I get the following error in our packages containing Pact tests:

ReferenceError: jasmine is not defined

  at ../../../node_modules/jest-pact/index.js:40:17

Presumably jest-pact has some kind of dependency on jasmine - I'm wondering if it's critical or can it be removed?

Error occurred in mock service: JSON::ParserError - 757: unexpected token at '"[{}]"'

I am using jest pact version - 0.9.1, when trying to make a post request , i get the following error

Error occurred in mock service: JSON::ParserError - 757: unexpected token at '"[]"'
node_modules/@pact-foundation/pact-node/standalone/darwin-1.88.81/pact/lib/vendor/ruby/2.2.0/gems/json-2.5.1/lib/json/common.rb:216:in `parse'

I am making post request using open api generated sdk.

Pact tests fail with timeout on pact server setup

Getting failing pact tests with error:

Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Error: Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.

Jest seems to start running tests before the pact server is up. Increasing the timeout range at index.js:19 seems to resolve this issue:

beforeAll(function () { return pactMock.setup(); }, 30000);

Using 0.4.5

Readme example - incorrect method name

Hi,

Thanks for putting this together, it's been really useful.

I think this part of the readme example:
it('returns server health', () => // implicit return again client.health().then(health => { expect(health).toEqual('up'); }));

Should in fact be:
it('returns server health', () => // implicit return again client.getHealth().then(health => { expect(health).toEqual('up'); }));

Support for @pact-foundation/pact v13

Checklist

Before making a feature request, I have:

Feature description

Support for the new major version (v13) of @pact-foundation/pact.

Use case

Pact files are generated in my project using jest-pact, and I would like to update @pact-foundation/pact to it's latest version.

Error after bumping up @pact-foundation/pact to v13:

npm error code ERESOLVE
npm error ERESOLVE could not resolve
npm error
npm error While resolving: [email protected]
npm error Found: @pact-foundation/[email protected]
npm error node_modules/@pact-foundation/pact
npm error   dev @pact-foundation/pact@"^13.0.0" from the root project

[DepShield] (CVSS 7.4) Vulnerability due to usage of lodash.isundefined:3.0.1

Vulnerabilities

DepShield reports that this application's usage of lodash.isundefined:3.0.1 results in the following vulnerability(s):


Occurrences

lodash.isundefined:3.0.1 is a transitive dependency introduced by the following direct dependency(s):

@pact-foundation/pact:8.2.2
        └─ lodash.isundefined:3.0.1

This is an automated GitHub Issue created by Sonatype DepShield. Details on managing GitHub Apps, including DepShield, are available for personal and organization accounts. Please submit questions or feedback about DepShield to the Sonatype DepShield Community.

[DepShield] (CVSS 7.4) Vulnerability due to usage of lodash.templatesettings:4.1.0

Vulnerabilities

DepShield reports that this application's usage of lodash.templatesettings:4.1.0 results in the following vulnerability(s):


Occurrences

lodash.templatesettings:4.1.0 is a transitive dependency introduced by the following direct dependency(s):

@commitlint/cli:7.6.1
        └─ @commitlint/read:7.6.0
              └─ git-raw-commits:1.3.6
                    └─ lodash.template:4.4.0
                          └─ lodash.templatesettings:4.1.0

This is an automated GitHub Issue created by Sonatype DepShield. Details on managing GitHub Apps, including DepShield, are available for personal and organization accounts. Please submit questions or feedback about DepShield to the Sonatype DepShield Community.

future proofing `jest-pact` / `jasmine is undefined`

jest provides a function that you can use per test file to override the test timeout. It works across all test-runners, which is important, since right now jest-pact only works if you're using the jasmine runner.

In jest@26 they've added a new runner, jest-circus, and in react-scripts@4 that is the default testRunner, so jasmine is no longer a thing. In jest@27 jest-circus will be the default for jest period, and in jest@28 you'll have to explicitly install the jasmine runner yourself to be able to use it.

I am aware that currently jest-pact specifies a peer dependency of a very small subset of jests, but react-scripts@4 is coming, and it's bringing jest@26 & jest-circus with it.

package versions:

jest-pact: 0.7.0
@pact-foundation/pact: 9.11.1
jest: 26.4.0 (yes, I am aware this is outside the defined peerDependency range)

repro:

clone https://github.com/cah-timhuddle/jest-pact-bug-repro
install the dependencies and run npm test
you'll be able to see the jasmine is undefined

[DepShield] (CVSS 7.4) Vulnerability due to usage of lodash.mergewith:4.6.1

Vulnerabilities

DepShield reports that this application's usage of lodash.mergewith:4.6.1 results in the following vulnerability(s):


Occurrences

lodash.mergewith:4.6.1 is a transitive dependency introduced by the following direct dependency(s):

newman:4.5.0
        └─ postman-collection:3.4.8
              └─ sanitize-html:1.20.1
                    └─ lodash.mergewith:4.6.1

This is an automated GitHub Issue created by Sonatype DepShield. Details on managing GitHub Apps, including DepShield, are available for personal and organization accounts. Please submit questions or feedback about DepShield to the Sonatype DepShield Community.

[DepShield] (CVSS 7.4) Vulnerability due to usage of lodash.uniq:4.5.0

Vulnerabilities

DepShield reports that this application's usage of lodash.uniq:4.5.0 results in the following vulnerability(s):


Occurrences

lodash.uniq:4.5.0 is a transitive dependency introduced by the following direct dependency(s):

@pact-foundation/pact:8.2.2
        └─ @pact-foundation/pact-node:8.2.0
              └─ caporal:1.1.0
                    └─ tabtab:2.2.2
                          └─ lodash.uniq:4.5.0

This is an automated GitHub Issue created by Sonatype DepShield. Details on managing GitHub Apps, including DepShield, are available for personal and organization accounts. Please submit questions or feedback about DepShield to the Sonatype DepShield Community.

Pact Verification Failed for multipart/form-data request

I am writing consumer pact test and application is react and test frame work is jest enzyme.
multipart/form-data request as bellow,

pactWith({ consumer: "example-react-site", 
           provider: "example-api",
           logLevel:"debug",
           port: 1234
        }, provider => {
    beforeAll(() => {
        provider.removeInteractions();
    });
    beforeEach(() => {
        Constants.baseUrl = provider.mockService.baseUrl;
    });

    describe("example api endpoint", () => {
        beforeEach(async () => {
            const file = path.join(__dirname, "./", "new_file.txt");
            const data = fs.readFileSync(file);
            const rawData = atob(data);
            const formData = `----------------------------771442083308144732506745
Content-Disposition: form-data; name="model"

{
    "returnUrl": "returnurl",
    "matterReference": "test matters",
    "emailTemplate": {
        "subject": "test",
        "body": "test"
    },
    "recipients": [
        {
            "name": "test",
            "email": "[email protected]",
            "order": 1,
            "anchors": [
                {
                    "name": "<!purchaser1Signer>",
                    "mandatory": false,
                    "type": "fullName",
                    "fontColor": null,
                    "buttonText": null,
                    "bold": false,
                    "italic": false,
                    "locked": false
                }
            ]
        }
    ]
}
----------------------------771442083308144732506745
Content-Disposition: form-data; name="files"; filename="doc.pdf"

${rawData}
----------------------------771442083308144732506745--
`.replace(/\n/gi, '\r\n');

            provider.addInteraction({
                state: "example service has a document and recipients",
                uponReceiving: "a request to digitally sign a document",
                withRequest: {
                    method: "POST",
                    path: "/example/sign",
                    headers: {
                        "Content-Type": string("multipart/form-data; boundary=--------------------------771442083308144732506745"),
                        "Accept": string('application/json')
                    },
                    body: string(formData)
                },
                willRespondWith: {
                    status: 200,
                    headers: {
                        "Content-Type": string('application/json; charset=UTF-8')
                    },
                    body: {
                        responseId: string("OR-12345")
                    }
                }
            })
        });

        it("should send document sign", async () => {
            //test implementation
        });
    });
    }); 
});

new_file.txt : base64 encode file

Jest setup as follows.

"jest": {
    "testResultsProcessor": "jest-teamcity-reporter",
    "verbose": true,
    "moduleDirectories": [
      "node_modules",
      "src/taskpane"
    ],
    "roots": [
      "<rootDir>/src/taskpane"
    ],
    "testMatch": [
      "**/__tests__/**/*.+(ts|tsx|js)",
      "**/?(*.)+(spec|test).?(pact).+(ts|tsx|js)"
    ],
    "transform": {
      "^.+\\.(ts|tsx)$": "ts-jest",
      "^.+\\.(js|jsx)$": "babel-jest"
    },
    "snapshotSerializers": [
      "enzyme-to-json/serializer"
    ],
    "setupFiles": [
      "./src/setupJest.js"
    ],
    "moduleNameMapper": {
      "^.+\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga|css|less|scss)$": "<rootDir>/src/taskpane/__mocks__/fileMock.js"
    },
    "testEnvironment": "node",
    "testTimeout": 12000
  }

Behaviour:
I am getting Pact verification failed as bellow,

  console.error
      at node_modules/@pact-foundation/src/httpPact.ts:118:17

  console.error
    Pact verification failed!

      at node_modules/@pact-foundation/src/httpPact.ts:119:17

  console.error
    Actual interactions do not match expected interactions for mock MockService.
    
    Missing requests:
        POST /example/sign
    
    Unexpected requests:
        POST /example/sign
    
    See path/pact/logs/mockserver-integration.log for details.
    

      at node_modules/@pact-foundation/src/httpPact.ts:120:17

Pact between example-react-site and example-api › with 30000 ms timeout for Pact › example api endpoint › should send document to sign

using,
jest: 26.0.1
jest-pact: 0.5.4

But if I remove generated log file and run pact test it will run successfully all the time.
wonder what is happening and possible fix.

[DepShield] (CVSS 7.4) Vulnerability due to usage of lodash.difference:4.5.0

Vulnerabilities

DepShield reports that this application's usage of lodash.difference:4.5.0 results in the following vulnerability(s):


Occurrences

lodash.difference:4.5.0 is a transitive dependency introduced by the following direct dependency(s):

@pact-foundation/pact:8.2.2
        └─ @pact-foundation/pact-node:8.2.0
              └─ caporal:1.1.0
                    └─ tabtab:2.2.2
                          └─ lodash.difference:4.5.0

This is an automated GitHub Issue created by Sonatype DepShield. Details on managing GitHub Apps, including DepShield, are available for personal and organization accounts. Please submit questions or feedback about DepShield to the Sonatype DepShield Community.

[DepShield] (CVSS 6.5) Vulnerability due to usage of btoa:1.2.1

Vulnerabilities

DepShield reports that this application's usage of btoa:1.2.1 results in the following vulnerability(s):


Occurrences

btoa:1.2.1 is a transitive dependency introduced by the following direct dependency(s):

newman:4.5.0
        └─ postman-runtime:7.14.0
              └─ btoa:1.2.1

This is an automated GitHub Issue created by Sonatype DepShield. Details on managing GitHub Apps, including DepShield, are available for personal and organization accounts. Please submit questions or feedback about DepShield to the Sonatype DepShield Community.

[DepShield] (CVSS 7.4) Vulnerability due to usage of lodash.isequal:4.5.0

Vulnerabilities

DepShield reports that this application's usage of lodash.isequal:4.5.0 results in the following vulnerability(s):


Occurrences

lodash.isequal:4.5.0 is a transitive dependency introduced by the following direct dependency(s):

swagger-cli:2.2.1
        └─ swagger-parser:6.0.5
              └─ z-schema:3.25.1
                    └─ lodash.isequal:4.5.0

This is an automated GitHub Issue created by Sonatype DepShield. Details on managing GitHub Apps, including DepShield, are available for personal and organization accounts. Please submit questions or feedback about DepShield to the Sonatype DepShield Community.

Log file does not contain data for all tests

In evaluating Jest-Pact last week I discovered that, with multiple Pact tests executing with --runInBand, the log file is overwritten for each test in the run. This means that it does not contain log data for the earlier tests in the run, which makes debugging those tests a bit trickier.

Workaround: run the tests one at a time.

pact-js 10.0.0 not compatible with jest-pact 0.9.0-beta.v3

Software versions

Please provide at least OS and version of pact-js

  • OS: Windows 10
  • Pact Node version: 10.0.0-beta.62
  • Node Version: 16.15.0
  • Other Versions: jest-pact 0.9.0-beta.v3

Issue Checklist

Please confirm the following:

  • I have upgraded to the latest
  • I have the read the FAQs in the Readme
  • I have triple checked, that there are no unhandled promises in my code
  • I have set my log level to debug and attached a log file showing the complete request/response cycle
  • For bonus points and virtual high fives, I have created a reproduceable git repository (see below) to illustrate the problem

Expected behaviour

Compiling the source code and importing

import { pactWith } from "jest-pact/v3";
works.

Actual behaviour

The test is not compiling, because in the jest-pact/v3/index.js there is an import

var pactV3 = require("@pact-foundation/pact/v3"); which should be (with beta.62)

var pactV3 = require("@pact-foundation/pact");

and then compilation works again.

Relevant log files

` Cannot find module '@pact-foundation/pact/v3' from '../../node_modules/.pnpm/[email protected]_bd5bdb562262fe533fb9de65840e42f8/node_modules/jest-pact/v3/index.js'

Require stack:
  C:/repos/xxx/xxx/frontend/node_modules/.pnpm/[email protected]_bd5bdb562262fe533fb9de65840e42f8/node_modules/jest-pact/v3/index.js
  src/__tests__/api/pact/XXX.pacttest.ts

  at Resolver.resolveModule (../../node_modules/.pnpm/[email protected]/node_modules/jest-resolve/build/resolver.js:324:11)`

move to pact-foundation org/scope

Currently this package is publishing from my personal npm account, makes sense to get it publishing under the pact-foundation

  • create pact-foundation org in npm

Other tasks will be picked up under #208 for the move to GH actions

[DepShield] (CVSS 7.4) Vulnerability due to usage of lodash.get:4.4.2

Vulnerabilities

DepShield reports that this application's usage of lodash.get:4.4.2 results in the following vulnerability(s):


Occurrences

lodash.get:4.4.2 is a transitive dependency introduced by the following direct dependency(s):

swagger-cli:2.2.1
        └─ swagger-parser:6.0.5
              └─ z-schema:3.25.1
                    └─ lodash.get:4.4.2

This is an automated GitHub Issue created by Sonatype DepShield. Details on managing GitHub Apps, including DepShield, are available for personal and organization accounts. Please submit questions or feedback about DepShield to the Sonatype DepShield Community.

Jest 27 support

Because of the peer dependencies, jest-pact can't be used with jest@27.

In my project, this leads to a dependency conflict with @angular-builders/jest@12.

It would be great if jest-pact supports jest@27 :)

@pact-foundation/pact/dist/pact does not exist in pact foundation folder

I Receive this error after running the test:

    Cannot find module '@pact-foundation/pact/dist/pact' from 'index.js'

      at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:259:17)
      at Object.<anonymous> (node_modules/jest-pact/index.js:14:12)

the folder /dist/pact does not exist in @pact-foundation/pact
Versions of the packages

    "@pact-foundation/pact": "^9.5.0",
    "jest": "^24.9.0",
    "jest-pact": "^0.5.0-beta"

[DepShield] (CVSS 7.4) Vulnerability due to usage of lodash.clonedeep:4.5.0

Vulnerabilities

DepShield reports that this application's usage of lodash.clonedeep:4.5.0 results in the following vulnerability(s):


Occurrences

lodash.clonedeep:4.5.0 is a transitive dependency introduced by the following direct dependency(s):

newman:4.5.0
        └─ postman-collection:3.4.8
              └─ sanitize-html:1.20.1
                    └─ lodash.clonedeep:4.5.0

This is an automated GitHub Issue created by Sonatype DepShield. Details on managing GitHub Apps, including DepShield, are available for personal and organization accounts. Please submit questions or feedback about DepShield to the Sonatype DepShield Community.

Pact V3 support

Hi,

We are using jest-pact in our project and would like to leverage some of the new features in Pact v3. I was wondering if/when v3 support could be added in jest-pact?

[DepShield] (CVSS 7.4) Vulnerability due to usage of lodash._reinterpolate:3.0.0

Vulnerabilities

DepShield reports that this application's usage of lodash._reinterpolate:3.0.0 results in the following vulnerability(s):


Occurrences

lodash._reinterpolate:3.0.0 is a transitive dependency introduced by the following direct dependency(s):

@commitlint/cli:7.6.1
        └─ @commitlint/read:7.6.0
              └─ git-raw-commits:1.3.6
                    └─ lodash.template:4.4.0
                          └─ lodash._reinterpolate:3.0.0
                          └─ lodash.templatesettings:4.1.0
                                └─ lodash._reinterpolate:3.0.0

This is an automated GitHub Issue created by Sonatype DepShield. Details on managing GitHub Apps, including DepShield, are available for personal and organization accounts. Please submit questions or feedback about DepShield to the Sonatype DepShield Community.

Logging in jest-pact V3 Beta

Hello!

I work in a project where we initially implemented the usual version of jest-pact and pact-foundation/pact, but we decided to migrate to Pact V3 Beta. Everything works fine and we are pleased with the change, but there seems to be an issue with logging. There is no documentation (at least I didn't find any) on logging for V3 and the pactWith() options no longer contain logging related properties.

My questions are: Is logging implemented in V3? Where can I get some documentation on it? And if it is not yet integrated in the beta version, when should we expect its integration?

Currently using:
@pact-foundation/pact: ^10.0.0-beta.54
jest-pact: ^0.9.0-beta.v3

Thanks!

[DepShield] (CVSS 7.4) Vulnerability due to usage of lodash.sortby:4.7.0

Vulnerabilities

DepShield reports that this application's usage of lodash.sortby:4.7.0 results in the following vulnerability(s):


Occurrences

lodash.sortby:4.7.0 is a transitive dependency introduced by the following direct dependency(s):

jest:24.7.1
        └─ jest-cli:24.7.1
              └─ jest-config:24.7.1
                    └─ jest-environment-jsdom:24.7.1
                          └─ jsdom:11.12.0
                                └─ data-urls:1.1.0
                                      └─ whatwg-url:7.0.0
                                            └─ lodash.sortby:4.7.0
                                └─ whatwg-url:6.5.0
                                      └─ lodash.sortby:4.7.0

This is an automated GitHub Issue created by Sonatype DepShield. Details on managing GitHub Apps, including DepShield, are available for personal and organization accounts. Please submit questions or feedback about DepShield to the Sonatype DepShield Community.

[DepShield] (CVSS 7.4) Vulnerability due to usage of lodash.isstring:4.0.1

Vulnerabilities

DepShield reports that this application's usage of lodash.isstring:4.0.1 results in the following vulnerability(s):


Occurrences

lodash.isstring:4.0.1 is a transitive dependency introduced by the following direct dependency(s):

newman:4.5.0
        └─ postman-collection:3.4.8
              └─ sanitize-html:1.20.1
                    └─ lodash.isstring:4.0.1

This is an automated GitHub Issue created by Sonatype DepShield. Details on managing GitHub Apps, including DepShield, are available for personal and organization accounts. Please submit questions or feedback about DepShield to the Sonatype DepShield Community.

Typescript Compiler failing with error TS2307

The following error is thrown when running tsc in my project:

node_modules/jest-pact/dist/types.d.ts:2:53 - error TS2307: Cannot find module '@pact-foundation/pact/dsl/options' or its corresponding type declarations.

2 import { MessageConsumerOptions, PactOptions } from '@pact-foundation/pact/dsl/options';

The issue seems to be stemming from this line:

} from '@pact-foundation/pact/dsl/options';

If I change the import to be
import { MessageConsumerOptions, PactOptions } from '@pact-foundation/pact'; or
import { MessageConsumerOptions, PactOptions } from '@pact-foundation/pact/src/dsl/options';
it works.

@pact-foundation/pact - version : 9.15.5
jest-pact - version: 0.8.3

Support newer jest versions

Currently, installing jest-pact with a newer jest version, like 25.2 ... displays peer dependency warnings.
Is there a reason, why newer versions of jest are not supported?
I have not seen any issues when running jest-pact with jest 25.2.3.

ci: move to GH actions

Move to GH actions to be in line with other repos

  • ci build for tests
  • ci build for releasing
  • master branch published
  • ensure changes ported to v3 branch
  • v3 branch published

[DepShield] (CVSS 7.4) Vulnerability due to usage of lodash.isplainobject:4.0.6

Vulnerabilities

DepShield reports that this application's usage of lodash.isplainobject:4.0.6 results in the following vulnerability(s):


Occurrences

lodash.isplainobject:4.0.6 is a transitive dependency introduced by the following direct dependency(s):

newman:4.5.0
        └─ postman-collection:3.4.8
              └─ sanitize-html:1.20.1
                    └─ lodash.isplainobject:4.0.6

This is an automated GitHub Issue created by Sonatype DepShield. Details on managing GitHub Apps, including DepShield, are available for personal and organization accounts. Please submit questions or feedback about DepShield to the Sonatype DepShield Community.

[DepShield] (CVSS 7.4) Vulnerability due to usage of lodash.escaperegexp:4.1.2

Vulnerabilities

DepShield reports that this application's usage of lodash.escaperegexp:4.1.2 results in the following vulnerability(s):


Occurrences

lodash.escaperegexp:4.1.2 is a transitive dependency introduced by the following direct dependency(s):

newman:4.5.0
        └─ postman-collection:3.4.8
              └─ sanitize-html:1.20.1
                    └─ lodash.escaperegexp:4.1.2

This is an automated GitHub Issue created by Sonatype DepShield. Details on managing GitHub Apps, including DepShield, are available for personal and organization accounts. Please submit questions or feedback about DepShield to the Sonatype DepShield Community.

[DepShield] (CVSS 7.4) Vulnerability due to usage of lodash.isfunction:3.0.8

Vulnerabilities

DepShield reports that this application's usage of lodash.isfunction:3.0.8 results in the following vulnerability(s):


Occurrences

lodash.isfunction:3.0.8 is a transitive dependency introduced by the following direct dependency(s):

@pact-foundation/pact:8.2.2
        └─ lodash.isfunction:3.0.8

This is an automated GitHub Issue created by Sonatype DepShield. Details on managing GitHub Apps, including DepShield, are available for personal and organization accounts. Please submit questions or feedback about DepShield to the Sonatype DepShield Community.

[DepShield] (CVSS 7.4) Vulnerability due to usage of lodash.template:4.4.0

Vulnerabilities

DepShield reports that this application's usage of lodash.template:4.4.0 results in the following vulnerability(s):


Occurrences

lodash.template:4.4.0 is a transitive dependency introduced by the following direct dependency(s):

@commitlint/cli:7.6.1
        └─ @commitlint/read:7.6.0
              └─ git-raw-commits:1.3.6
                    └─ lodash.template:4.4.0

standard-version:6.0.1
        └─ conventional-changelog:3.1.8
              └─ conventional-changelog-core:3.2.2
                    └─ git-raw-commits:2.0.0
                          └─ lodash.template:4.4.0
        └─ conventional-recommended-bump:5.0.0
              └─ git-raw-commits:2.0.0
                    └─ lodash.template:4.4.0

This is an automated GitHub Issue created by Sonatype DepShield. Details on managing GitHub Apps, including DepShield, are available for personal and organization accounts. Please submit questions or feedback about DepShield to the Sonatype DepShield Community.

[DepShield] (CVSS 7.4) Vulnerability due to usage of lodash.padstart:4.6.1

Vulnerabilities

DepShield reports that this application's usage of lodash.padstart:4.6.1 results in the following vulnerability(s):


Occurrences

lodash.padstart:4.6.1 is a transitive dependency introduced by the following direct dependency(s):

@pact-foundation/pact:8.2.2
        └─ @pact-foundation/pact-node:8.2.0
              └─ caporal:1.1.0
                    └─ tabtab:2.2.2
                          └─ npmlog:2.0.4
                                └─ gauge:1.2.7
                                      └─ lodash.padstart:4.6.1

This is an automated GitHub Issue created by Sonatype DepShield. Details on managing GitHub Apps, including DepShield, are available for personal and organization accounts. Please submit questions or feedback about DepShield to the Sonatype DepShield Community.

[DepShield] (CVSS 7.4) Vulnerability due to usage of lodash.camelcase:4.3.0

Vulnerabilities

DepShield reports that this application's usage of lodash.camelcase:4.3.0 results in the following vulnerability(s):


Occurrences

lodash.camelcase:4.3.0 is a transitive dependency introduced by the following direct dependency(s):

@pact-foundation/pact:8.2.2
        └─ @pact-foundation/pact-node:8.2.0
              └─ caporal:1.1.0
                    └─ lodash.camelcase:4.3.0
                    └─ micromist:1.1.0
                          └─ lodash.camelcase:4.3.0

This is an automated GitHub Issue created by Sonatype DepShield. Details on managing GitHub Apps, including DepShield, are available for personal and organization accounts. Please submit questions or feedback about DepShield to the Sonatype DepShield Community.

[DepShield] (CVSS 7.5) Vulnerability due to usage of debug:2.6.9

Vulnerabilities

DepShield reports that this application's usage of debug:2.6.9 results in the following vulnerability(s):


Occurrences

debug:2.6.9 is a transitive dependency introduced by the following direct dependency(s):

@pact-foundation/pact:8.2.4
        └─ @pact-foundation/pact-node:8.3.3
              └─ caporal:1.2.0
                    └─ tabtab:2.2.2
                          └─ debug:2.6.9
              └─ sumchecker:2.0.2
                    └─ debug:2.6.9
        └─ body-parser:1.19.0
              └─ debug:2.6.9
        └─ express:4.17.1
              └─ debug:2.6.9
              └─ finalhandler:1.1.2
                    └─ debug:2.6.9
              └─ send:0.17.1
                    └─ debug:2.6.9

lint-staged:8.1.6
        └─ micromatch:3.1.10
              └─ extglob:2.0.4
                    └─ expand-brackets:2.1.4
                          └─ debug:2.6.9
              └─ snapdragon:0.8.2
                    └─ debug:2.6.9

This is an automated GitHub Issue created by Sonatype DepShield. Details on managing GitHub Apps, including DepShield, are available for personal and organization accounts. Please submit questions or feedback about DepShield to the Sonatype DepShield Community.

Race condition

I am facing a race condition issue.
Sometimes the test passes, but more often than not it fails, since, the test runs before the provider adds the interaction, I figured out a few workarounds, however since my test looks a lot like the examples in the Readme, I'd like to know if I am doing something wrong, or if this is expected behavior
here is my test:

        consumer: "client",
        provider: "api:,
        log: path.resolve(process.cwd(), "logs", "pact.log"),
        dir: path.resolve(process.cwd(), "pacts"),
        logLevel: "INFO"
    },
    provider => {
        let client;
        beforeEach(() =>
            client = api({options: {baseURL: provider.mockService.baseUrl}})
        )
        describe("get event by id", () => {
            beforeEach(() => {
                provider.addInteraction({
                    state: "event id exists",
                    uponReceiving: "a request for an event with id anid",
                    willRespondWith: {
                        status: 200,
                        body: userRsvp
                    },
                    withRequest: {
                        method: 'GET',
                        path: "/meal/5ec69049-72c3-4a6c-b418-8036559fa335"
                    }
                })
            })
            it("returns an array of userMeal objects", () => {
                client.getUserMeals("5ec69049-72c3-4a6c-b418-8036559fa335").then(
                    meals => expect(rsvps.data.length).toEqual(1)
                )
            });
        });
    })

[DepShield] (CVSS 7.4) Vulnerability due to usage of lodash.omit:4.5.0

Vulnerabilities

DepShield reports that this application's usage of lodash.omit:4.5.0 results in the following vulnerability(s):


Occurrences

lodash.omit:4.5.0 is a transitive dependency introduced by the following direct dependency(s):

@pact-foundation/pact:8.2.2
        └─ lodash.omit:4.5.0

This is an automated GitHub Issue created by Sonatype DepShield. Details on managing GitHub Apps, including DepShield, are available for personal and organization accounts. Please submit questions or feedback about DepShield to the Sonatype DepShield Community.

[DepShield] (CVSS 7.4) Vulnerability due to usage of lodash.merge:4.6.1

Vulnerabilities

DepShield reports that this application's usage of lodash.merge:4.6.1 results in the following vulnerability(s):


Occurrences

lodash.merge:4.6.1 is a transitive dependency introduced by the following direct dependency(s):

@pact-foundation/pact:8.2.2
        └─ @pact-foundation/pact-node:8.2.0
              └─ caporal:1.1.0
                    └─ lodash.merge:4.6.1

This is an automated GitHub Issue created by Sonatype DepShield. Details on managing GitHub Apps, including DepShield, are available for personal and organization accounts. Please submit questions or feedback about DepShield to the Sonatype DepShield Community.

V3 DSL Feedback

Feature description

V3 API.

Use case

I made the same code using jest-pact v3

pactWith(pactConfig, (interaction) => {
  interaction('authentication api', ({ execute, provider }) => {
    const username = mockUsername;
    provider.addInteraction(validUsername({ username }));

    return execute(
      'can check for existence of username',
      async (mockServer) => {
        const response = await validateUsername({
          username,
          api: new Api(mockServer.url),
        });

        expect(response).toBeDefined();
      },
    );
  });
});

and plain pact v3:

describe('authentication', () => {
  it('can check for existence of username', () => {
    const username = mockUsername;
    provider.addInteraction(validUsername({ username }));
    
    return provider.executeTest(async (mockServer) => {
    const response =  await validateUsername({
        username,
        api: new Api(mockServer.url),
     expect(response).toBeDefined();
    });
  });
});

It seems to me that plain pact v3 syntax is way closer to jest and easier to understand. I have a clear separation between different interactions and only need to wrap my api calls with special executeTest method.
While with jest-pact I'm getting confused as I would need to add a NEW interaction for every single interaction that I do even, so my interaction already has a name defined.

I would suggest removing extra layer of interaction and provide ({ execute, provider}) directly in callback of pactWith. I presume pactWith just maps to describe, we should be able to use standard it blocks to separate tests instead of wrapping them in special syntax.

By interaction already has a name I mean my interaction already has:

uponReceiving: 'a POST request to validate the username',

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.