https://pact.io logo
Join Slack
Powered by
# pact-js
  • j

    John Nguyen

    11/11/2024, 8:33 PM
    Hello! I'm trying to get started with
    pact-js
    ,
    jest-pact
    , and
    SuperTest
    . I've got a simple consumer test written up, but at the verification stage I get an output that:
    Copy code
    Pact between Jest-Consumer-Example and Provider
        with 30000 ms timeout for Pact
    
    Pact verification failed - expected interactions did not match actual.
    with no additional information. Setting the logLevel in the configuration step to
    debug
    or
    trace
    doesn't give any useful information, and I can't find any log file saved elsewhere. I've verified through debugging that my API call does return the expected response at the point of calling the API, so I was hoping for advice on how I can get Pact to output more useful information (e.g. a comparison of what was expected vs what was received) about where I've gone wrong. Or if I may have made any obvious implementation mistakes. Thanks in advance, and please let me know what additional information might be useful!
    Copy code
    const url = '/path/to/endpoint'
    
    pactWith(
        {
            consumer: "Jest-Consumer-Example",
            provider: "Provider",
            logLevel: LOG_LEVEL as LogLevel,
            pactfileWriteMode: 'merge',
        },
        (provider) => {
            describe('The API', () => { 
                const itemExample = {
                    "NumberField": 3,
                }     
                const EXPECTED_BODY = {
                    results: eachLike(itemExample)
                }
                const itemSuccessResponse = {
                    status: 200,
                    body: EXPECTED_BODY,
                }
                const itemRequest = {
                    uponReceiving: 'a request for a thing',
                    withRequest: {
                        method: 'GET' as HTTPMethods,
                        path: url,
                    }
                }
    
                let agent: SuperAgentTest
                beforeEach(async () => {
                    agent = await AuthHelper.createAgent()
                    const interaction: InteractionObject = {
                        state: 'I have a thing',
                        ...itemRequest,
                        willRespondWith: itemSuccessResponse,
                    }
                    return provider.addInteraction(interaction)
                })
                it('returns a successful body', () => {
                    return agent.get(`${endpointPath}`)
                        .then((item) => {
                            console.log(item)
                        })
                })
            })
        }
    )
    m
    • 2
    • 6
  • d

    Damien Deloubes

    11/18/2024, 10:44 PM
    Hey! I am trying to setup the bi directional example using playwright and postman. However every time I run the:
    make ci PACT_BROKER_BASE_URL="..." PACT_BROKER_TOKEN="..." PACT_PROVIDER="..."
    I get the following error:
    Specified pact file 'pacts' does not exist. This sometimes indicates one of the arguments has been specified with the wrong name and has been incorrectly identified as a file path. If you are using Docker, check that you have mounted the pact file or directory into the container correctly using
    -v`, and have specified the location of the pact file or directory in the Docker container, not the host.`
    make: *** [publish_pacts] Error 1
    Has anyone encountered the same issue? I am still trying to wrap my head around it all and would love to learn from you all!
    m
    • 2
    • 23
  • a

    Andrei Enache

    11/27/2024, 10:30 AM
    Hi, I'm a software engineer at Booking.com, and we're working on setting up a Pact with a custom
    Content-Type: application/x-ndjson
    header in the response. However, after adding this header in the
    willRespondWith
    section, the response body format seems to be affected. We're seeing additional values like
    {\"value\":
    ,
    { \"value\": {}, \"pact:matcher:type\": \"type\" }
    , and others being included in the response. It looks like the matchers might be influencing the JSON serialization when the
    Content-Type
    is set to
    application/x-ndjson
    . For
    application/json
    , everything works as expected. Could we get some help resolving this? Thanks!
    m
    • 2
    • 9
  • j

    James P

    11/28/2024, 3:53 PM
    Hi, I’m trying to upgrade some of our js consumer. pact tests to use pact specification 3. I’m a bit confused about something. The test uses
    MatchersV3
    and has a property
    spec: 3
    but when the test runs, the pact file specifies version 2. I’ve tried changing to use
    Matchers
    but there is a
    eachLike
    function which has different behaviour - on
    MatchersV3
    it will allow 0 but on
    Matchers
    is wont. So I have 2 questions: 1. Why is the specification coming out as Version 2 when I specify 3? 2. Why has the eachLike behaviour changed so that 0 is no longer a valid case?
    m
    • 2
    • 5
  • v

    Val Kolovos

    12/04/2024, 8:22 PM
    I feel like I've asked this question before, but... does PactJS support V3/V4 Async Message testing?
    m
    • 2
    • 8
  • m

    Matt (pactflow.io / pact-js / pact-go)

    12/05/2024, 9:17 AM
    📣 Just a quick FYI to let people know that we’ve recently added renovate to the project, and there are a lot of PRs we’re sorting through. Probably will take a few days by the time they are all merged/closed, so please just be aware in case you submit a PR or are actively working on the code base. I’ll aim to rip the 🩹 off quickly here rather than draw it out
  • y

    Yalim Yasaroglu

    12/12/2024, 2:05 PM
    Hi everyone, 👋 I’m running into an issue with the Pact-JS Verifier when trying to verify multipart uploads. It seems like the proxy server that the verifier bootstraps can’t handle requests larger than a certain size. I suspect this might be because it uses
    body-parser
    middleware, which has a default size limit of ~100KB. Does anyone know if there’s a way to increase this limit or configure the verifier to handle larger payloads? Or am I missing something in the setup? Any advice would be much appreciated! 🙏 Thanks!
    m
    • 2
    • 1
  • j

    Jeu Manzo

    12/16/2024, 11:03 PM
    Hello, when trying to generate a contract test using pactflow-ai I'm getting this error:
    Client error: 403 Forbidden Failed to create session
    I have set the env variables, and even get the following output when running
    pactflow-ai status
    m
    j
    • 3
    • 5
  • l

    Luis Nuño

    12/23/2024, 9:14 PM
    Hello! We have a jenkins job that runs our consumer tests and publish the contract to PactFlow, but it suddenly starting failing a couple of days ago,. In the log we can see the next error message:
    Copy code
    15:08:15  [15:08:15.632] DEBUG (676): pact@13.2.0: mock service started on port: 8081
    15:08:45  [15:08:45.635] ERROR (677): pact@13.2.0: The pact mock service doesn't appear to be running
    15:08:45    - Please check the logs above to ensure that there are no pact service startup failures
    15:08:45    - Please check that pact lifecycle methods are called in the correct order (setup() needs to be called before this method)
    15:08:45    - Please check that your test code waits for the promises returned from lifecycle methods to complete before calling the next one
    15:08:45    - To learn more about what is happening during your pact run, try setting logLevel: 'DEBUG'
    We tried changing the port but it doesn't matter which port we use we always get the same error. I also tried to run the tests locally and I also get the exact same errors, which is also weird since everything was working fine last week 🤔 Do you know what may be causing this error?
    m
    • 2
    • 5
  • d

    Dmitry Munda

    01/02/2025, 3:07 PM
    hi! bumped pact to
    Copy code
    "@pact-foundation/pact": "13.2.0",
  • a

    Abubakar Mehmood

    01/06/2025, 4:08 PM
    Hello, Team! I'm using PactJS and publishing the pact programmatically. The pact gets published to the Pactflow broker successfully but the
    then
    handler is never called.
    Similarly, if there's an error (e.g. I remove the broker token from the environment variables), the
    error
    handler is never called.
    Also, the
    finally
    callback is never called in either case. Here's my code.
    Copy code
    pact.publishPacts(opts)
            .then(function() {
              console.log(`Published pact successfully. It should be updated on ${brokerUrl}.`);
            })
            .catch(function(err) {
              console.error('Failed to publish pact:', err);
            })
            .finally(function() {
              console.log('i am in finally');
            });
    I only see the following log messages:
    Copy code
    [16:06:01.224] INFO (89029): pact-node@10.18.0: Publishing Pacts to Broker
    [16:06:01.225] INFO (89029): pact-node@10.18.0: Publishing pacts to broker at: https://*****.<http://pactflow.io|pactflow.io>
    Is this a known issue or am I doing something completely wrong? (The reason for publishing in JS is that the logic of publishing the pact conditionally, and applying the right tags etc. is more readable and testable)
    m
    • 2
    • 6
  • h

    Hernan Mateika

    01/15/2025, 3:40 PM
    Hi! I am using
    pact-js
    (Using PactV4) with jest and i am having some issues when creating the contract since I have consumer tests splitted in diferent files and pact json file doesnt display all interactions, just the latest one. is there any config that i am missing? I have found some references to this but it seems its not there anymore. https://github.com/pact-foundation/docs.pact.io/issues/155#:~:text=https%3A//docs.pact.io/implementati[…]litting%2Dtests%2Dacross%2Dmultiple%2Dfiles
    m
    • 2
    • 11
  • v

    Val Kolovos

    02/06/2025, 7:58 PM
    Has anyone here created a consumer-side pact (v4) that includes both synchronous (http) and asynchronous interactions?
    m
    y
    • 3
    • 18
  • b

    Bas Dijkstra

    02/11/2025, 9:19 AM
    Hey folks, quick question. A coworker has trouble running our Pact consumer tests on their machine. It seems to throw a connection refused error either when the Pact mock server is started, or when the first request hits it. The exact same tests work on other people's machines, including mine, without problems. Same Node version, same Pact library versions, same OS. What we already tried: • Running tests from an elevated CLI / IDE • Cleaning and reinstalling all
    node_modules
    • Checking if there's something running on port
    4010
    - there isn't, or at least
    netstat
    doesn't show it Any ideas? I've attached the debug Pact log from their machine for more info.
    out.txt
    m
    • 2
    • 22
  • s

    Spencer

    02/11/2025, 3:34 PM
    @Spencer has left the channel
  • f

    Frank Rosner

    02/24/2025, 2:57 PM
    QQ: Does anyone know if it's possible to do regex matching on text/plain responses in consumer tests? I am trying to generate something like https://github.com/pact-foundation/pact-jvm/blob/master/pact-specification-test/sr[…]onse/body/plain%20text%20regex%20matching%20missing%20body.json, but the V4 response builder interface seems to have only an option to pass a buffer and no matchers?
    Copy code
    export interface V4ResponseBuilder {
        headers(headers: TemplateHeaders): V4ResponseBuilder;
        jsonBody(body: unknown): V4ResponseBuilder;
        binaryFile(contentType: string, file: string): V4ResponseBuilder;
        multipartBody(contentType: string, filename: string, mimePartName: string): V4ResponseBuilder;
        body(contentType: string, body: Buffer): V4ResponseBuilder;
    }
    m
    r
    j
    • 4
    • 24
  • m

    Martin Mineo

    03/07/2025, 1:16 PM
    @Martin Mineo has left the channel
  • b

    Bertrand Ernst

    03/13/2025, 1:25 PM
    Hello folks ! I was wondering if it is possible to manage the pact-mock server outside of
    pact-js
    ? To be more precise, I would like to manage the mock server myself using the
    pact-cli
    Docker image instead of having
    pact-js
    launch a mock-server for me. I looked at the options to setup the provider with the
    host
    and
    port
    of a running mock-server but couldn't find anything. Is this at all possible? Thanks in advance !
    y
    • 2
    • 3
  • g

    Gabriel Vasconcelos

    03/17/2025, 2:04 PM
    Hello team, how can I validate an enum of integers in pact JS? Is it possible? or only for strings?
    m
    r
    • 3
    • 13
  • l

    Lachlan Newman

    03/18/2025, 5:05 AM
    hey guys is there a way to use matchers to be one of a union type ? for example i want a key to be of type null or any string ?
    m
    s
    • 3
    • 4
  • b

    Bertrand Ernst

    03/28/2025, 11:05 AM
    Hey guys ! I use
    pact-js
    along with
    jest
    . Above every test suite that is executed, I have the following error message:
    Copy code
    Failed to initialise global tracing subscriber - a global default trace dispatcher has already been set
    As I understand, this comes from the reference implementation where there are several instance of such error message being sent: https://github.com/search?q=repo%3Apact-foundation%2Fpact-reference%20set_global_default&amp;type=code I initialize my provider using
    new PactV3(...)
    in a
    beforeEach
    block within a
    setupFilesAfterEnv
    file (is this best practice?). https://jestjs.io/docs/configuration#setupfilesafterenv-array What is the best way to get rid of this error? Note that it's not blocking, my tests run just as well but it's annoying. 🙂
    m
    • 2
    • 2
  • a

    Abubakar Mehmood

    03/31/2025, 10:24 AM
    Hello, folks! Have successfully published a consumer pact to Pactflow but having trouble verifying it from the provider. The provider is a NodeJS lambda function in which I start a server and essentially following the provider and its test from the e2e example. Facing two problems: 1. pactjs tries to hit the
    /_pactSetup
    endpoint but I haven't set it up
    (neither does the above-mentioned example). Logs:
    Copy code
    2025-03-31T07:33:34.581653Z DEBUG ThreadId(02) verify_interaction{interaction="a request to create a quote"}: hyper_util::client::legacy::connect::http: connecting to 127.0.0.1:51891
    2025-03-31T07:33:34.581929Z DEBUG ThreadId(02) verify_interaction{interaction="a request to create a quote"}: hyper_util::client::legacy::connect::http: connected to 127.0.0.1:51891
    [08:33:34.604] DEBUG (38248): pact@15.0.1: hooks state counter is 1 after receiving "setup" action
    [08:33:34.605] DEBUG (38248): pact@15.0.1: incoming request: {"body":{"action":"setup","params":{},"state":"quote can be created"},"headers":{"content-type":"application/json","accept":"*/*","accept-encoding":"gzip, deflate","host":"127.0.0.1:51891","content-length":"61"},"method":"POST","path":"/_pactSetup"}
    
    (followed by timeout)
    
    2025-03-31T07:34:04.691883Z DEBUG ThreadId(02) verify_interaction{interaction="a request to create a quote"}: pact_verifier::provider_client: State change request failed with error error sending request for url (<http://127.0.0.1:51891/_pactSetup>)
    While the docs here seem to mention that we need to set up an (or two, according to this old answer) HTTP endpoints for the states, I couldn't find any details of what the endpoints should look like, and how are the e2e tests working without setting up those endpoints. 2. pactjs seems to start its own mock server and call the endpoint to verify on that base URL instead of using the
    providerBaseUrl
    I've specified
    . Excerpt of code:
    Copy code
    const server = express();
    server.use(cors());
    const app = server.listen(53404, () => {
    console.log(`Server listening on <http://localhost:53404>`);
    });
    server.post('/v3/forex/quote', (req, res) => {
    res.append('Content-Type', 'application/json').status(200).send({
    dummy: 123456789, // This is supposed to be replaced in the request filters
    });
    });
    
    const opts = {
                provider: 'MyProvider',
                logLevel: "debug",
                providerBaseUrl: `<http://localhost:53404>`,
                stateHandlers: {
                    'quote can be created': async () => {
                        await redisClient.set("some data");
                        //console.log('handler finished');
                        return Promise.resolve();
                    },
                },
               
                // Override request handling to call the Lambda function directly
                requestFilter: async (req, res, next) => {
                 // omitted for brevity
                 }
            };
            const verifier = new Verifier(opts);
    Logs show a different port (53741), instead of 53404. It changes every time, though:
    Copy code
    2025-03-31T08:39:11.753646Z INFO ThreadId(02) verify_interaction{interaction="a request to create a quote"}: pact_verifier::provider_client: Sending request to provider at <http://127.0.0.1:53741/>
    2025-03-31T08:39:11.753655Z DEBUG ThreadId(02) verify_interaction{interaction="a request to create a quote"}: pact_verifier::provider_client: Provider details = ProviderInfo { name: "ForexV3-Funding", protocol: "http", host: "127.0.0.1", port: Some(53741), path: "/", transports: [ProviderTransport { transport: "http", port: Some(53741), path: Some("/"), scheme: Some("http") }] }
    2025-03-31T08:39:11.753676Z INFO ThreadId(02) verify_interaction{interaction="a request to create a quote"}: pact_verifier::provider_client: Sending request HTTP Request ( method: POST, path: /v3/forex/quote, query: None, headers: Some({"Content-Type": ["application/json"]}), body: Present(115 bytes, application/json) )
    2025-03-31T08:39:11.753689Z DEBUG ThreadId(02) verify_interaction{interaction="a request to create a quote"}: pact_verifier::provider_client: body:
    {"buy_amount":"18.358","buy_currency":"GBP","customer":{"id":"C-98YE32ZY"},"sell_currency":"USD","type":"customer"}
    2025-03-31T08:39:11.753743Z DEBUG ThreadId(02) verify_interaction{interaction="a request to create a quote"}: hyper_util::client::legacy::pool: reuse idle connection for ("http", 127.0.0.1:53741)
    [09:39:11.756] DEBUG (40620): pact@15.0.1: incoming request: {"body":{"buy_amount":"18.358","buy_currency":"GBP","customer":{"id":"C-98YE32ZY"},"sell_currency":"USD","type":"customer"},"headers":{"content-type":"application/json","accept":"*/*","accept-encoding":"gzip, deflate","host":"127.0.0.1:53741","content-length":"115"},"method":"POST","path":"/v3/forex/quote"}
    m
    • 2
    • 2
  • a

    Ayoub BOULAHTAR

    04/04/2025, 11:05 AM
    Hello community, I'm trying to write JS consumer tests with pact and vitest testing framework, I'm using PactV4, MatchersV3 from @pact-foundation/pact I can't find how to test a list of integers in the query builder, cf the code below, can anyone provide some insights please ?
    Copy code
    provider
    .addInteraction()
    .given('one or more requested row exist')
    .withRequest('GET', '/base/url', (builder) => {
      builder.query({
        ids: MatchersV3.eachLike(1),
      });
      builder.headers({
        'Content-Type': 'application/json',
      });
    })
    m
    • 2
    • 5
  • r

    Ruud Welling

    04/25/2025, 3:05 PM
    Hello, I am try to create a consumer test of a synchrounous message pact in pact-js. However I noticed several things: • The documentation about this is empty: https://docs.pact.io/implementation_guides/javascript/docs/messages#contract-testing-process-synchronous • I could not find any tests for this feature in the sdk (while looking for examples) The DSL seems to support creation of these tests, however when I run the test the contract file does not have a request and response. Is this feature not supported?
    m
    • 2
    • 3
  • n

    Neil McLaughlin

    05/02/2025, 9:03 AM
    Hi, I have a pact consumer test written in typescript. We are on “@pact-foundation/pact”: “^15.0.1". The test is currently working, but I would like to parameterise the url to make the contract somewhat less brittle. I’ve done this successfully in the past with the
    fromProviderState
    using the
    V3Interaction
    , but I can’t seem to get it working with the
    V4Interaction
    model. The
    fromProviderState
    call initially seems like its working in that the test passes, but the mock server seems to match any path, not just the specified path. Also, I’ve noticed that this method seems to have been dropped from the documentation in both the Java and JS versions of the pact documentation. The initial version (static path) is working, but it bakes a specific id into the contract.
    Copy code
    v4InteractionWithResponse = mockServer
          .addInteraction()
          .uponReceiving("a request for an advert")
          .given("basic car advert")
          .withRequest(
            "GET",
            "/product-page/v1/advert/201602281465747",
            (builder) => {
              builder.query({ channel: "cars" });
            },
          )
    So the next step was to parameterize the path using
    fromProviderState
    .
    Copy code
    v4InteractionWithResponse = mockServer
          .addInteraction()
          .uponReceiving("a request for an advert")
          .given("basic car advert")
          .withRequest(
            "GET",
            fromProviderState(
              "/product-page/v1/advert/${advertId}",
              "/product-page/v1/advert/201602281465747",
            ),
            (builder) => {
              builder.query({ channel: "cars" });
            },
          )
  • y

    Yassen Damyanov

    05/10/2025, 4:50 PM
    Hey Pact community 👋 Quick question: is pact-js V3 still affected by this issue of representing
    Accept
    header values as an array as opposed to a comma delimited string? Details in 💬 ➡️
    m
    • 2
    • 4
  • j

    Jesse Vander Does

    05/19/2025, 2:35 PM
    Hi team, I have an API that is sending multipart/form-data containing both a binary and JSON data. I'm particularly interested in verifying the JSON data. I'm using PactV4 and have code like this. Two main questions: • When I add this sort of header declaration, I don't see anything related to the header show up in the pact file, why is that? • Is there a way that I can capture the contract that the server should handle the portion of the form containing JSON? I have seen some scattered references to multipart form data, but it seems like it may be for V3. I also couldn't find good examples for defining the structure of data within the form. Thanks in advance for any help.
    Copy code
    provider     
          .addInteraction()
          .given('a valid record can be saved')
          .uponReceiving('a request to save a record')
          .withRequest('POST', `/api/resource/${id}`, (builder) => {
            builder.headers(
                'multipart/form-data; boundary=.*',
            );
           })
    m
    • 2
    • 7
  • v

    Victor COATALEM

    06/19/2025, 10:31 AM
    Hello 👋 I am trying to write a consumer test on pact-js V3. The request I want to test is a multipart form request , which contains a file as well as JSON metadata fields (
    source, reason, ...
    ). Basically I don't care about the file in itself, but I want to write matchers on the metadata fields. However I can't seem to make that work. Matching the
    reason
    field against anything yields the error:
    Failed to parse the expected body as a MIME multipart body: 'incomplete multipart stream'
    . I posted my example on this issue . Any input would be greatly appreciated 🙏
    m
    • 2
    • 3
  • t

    Teresa Marcelino

    06/23/2025, 3:32 PM
    Hey team 👋, I’m hitting a Pact test failure with a
    DELETE
    request. The mock expects a JSON request body like this:
    Copy code
    {
      "objectsIds": [
        1,
        2,
        3
      ]
    }
    But the test fails sayingfail:
    Expected body Present(45 bytes, application/json) but was empty
    My request call looks like this:
    Copy code
    makeRequestAcceptingJsonResponse("DELETE", mockServer.url, path, {
      objectsIds: [1, 2, 3],
    } /*payload*/);
    And my request function:
    Copy code
    return axios.request({
      baseURL,
      data: payload,
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
      method,
      url: path,
      validateStatus: () => true,
    });
    I suspect Axios might be dropping the body on DELETE requests. If I change to a POST, request body is being sent correctly. Has anyone seen this or knows how to fix it? Thanks! 🙏
    m
    y
    • 3
    • 4
  • z

    Zachary Lysobey

    06/24/2025, 9:40 PM
    I'm trying to figure out how to improve this section of the
    pact-js
    docs on Provider verification: > https://github.com/pact-foundation/pact-js/blob/master/docs/provider.md?plain=1#L122-L125
    Copy code
    const opts = {
      ...
      stateHandlers: {
        [null]: () => {
          // This is the "default" state handler, when no state is given
        }
        "Has no animals": () => {
          // ...
    There are a couple issues with this. 1) just above, it says "Here is an example from our e2e suite:". But the
    [null]
    case is not part of that example 2) its missing a comma after the
    [null]
    case, so the syntax is broken. 3) This works in JavaScript, but does not in TypeScript. TS is stricter with computed properties:
    > A computed property name must be of type 'string', 'number', 'symbol', or 'any'
    I think
    [null]
    would be coerced into
    "null"
    at runtime with JS, so maybe that works? I'm happy to make a PR fixing this. I'd of course add the missing
    ,
    , and I guess update
    [null]
    to be just
    "null"
    (?). But I'm not sure what to do about
    1)
    with the inaccurate note about the example code. Any advice?
    m
    • 2
    • 4