https://pact.io logo
Join SlackCommunities
Powered by
# pact-js
  • y

    Yauheni Butski

    10/14/2024, 1:48 PM
    Hi! Does exist way to set up pact file rewrite mode? I remember in previous versions it was a possibility to set as option in constructor 'new Pact({...}])" Problem: When you generate pact file and then change something in pair ".given(..) +.uponReceiving(..)" it will just add in file as new interaction (so old remains and new added). So, any way how to do it? Right now I just remove file and re-generate it again, as generation from single source.
    m
    • 2
    • 2
  • y

    Yauheni Butski

    10/14/2024, 1:55 PM
    And one more question (or better to say, ask for suggestions). If I have "serviceA" as consumer (for example front-end) and "serviceB" as provider (for example backend). And on backend I have like 10, 20, N controllers/endpoints. So I don't want to have everything in one large file "serviceA-serviceB.json". I would like to split it based on controllers at least. The only way that I see is just modify consumer name and have separate tests. Like: "serviceA-users-serviceB.json", "serviceA-orders-serviceB.json", "serviceA-comments-serviceB.json" Any other better ideas based on your experience?
    m
    • 2
    • 2
  • m

    Murat Ozcan

    10/16/2024, 4:15 PM
    Here’s my latest blog post where I tackle cross-execution challenges in Pact testing with Kafka message queues, alongside traditional consumer-driven contract testing using multiple contracts in the same repository. If you’re dealing with similar issues or are interested in improving your contract testing with Pact for both consumer-driven contracts and message queue testing, I invite you to give it a read. I’d love to hear your thoughts and experiences on this topic @Matt (pactflow.io / pact-js / pact-go) @Yousaf Nabi (pactflow.io) https://dev.to/muratkeremozcan/solving-cross-execution-issues-in-pact-testing-with-kafka-and-message-queues-2d2g
    m
    • 2
    • 2
  • l

    Luis Nuño

    10/17/2024, 5:44 PM
    Hi everyone! A couple of months ago, while working on a Bi-Directional Contract Testing project, we faced an issue that took us several days to fix. We published the contract generated by the Consumer and the OAS from the Provider to PactFlow and we got a Validation Error:
    Cannot read properties of undefined (reading 'type')
    There was nothing else than that, no further details, nothing that could point us to the cause of the error or where to find it, and after the error all tests were marked as passed. After several days we finally found the cause of the problem, a typo in a parameter's name in the OAS, yes it was a dumb issue, but hard to find in an OAS with 3k+ lines. After fixing the param name, the error was not displayed anymore, but additional and more specific validation errors appeared, this time related to some of our tests, such as datatypes mismatches, missing body attributes, etc, errors that were easily fixed but that were originally masked/hidden by the "Cannot read properties of undefined (reading 'type')" error. Now, we are working on a new Bi-Directional Contract Testing project and this time we started with a single test on the consumer side and with a simple OAS with only 5 endpoints, we published the contract and the spec file to PactFlow and one more time we have a
    Cannot read properties of undefined (reading 'type')
    validation error. We carefully checked the OAS and this time we have no typos or param issues and we have no idea of what may be causing this error. We have searched information about this error and it looks like it is very generic, it is displayed under many different circumstances. We are stuck and we have no clue on what may be causing the issue this time, so I would really appreciate if you have any suggestion/input/tip on where/what to check.
    m
    • 2
    • 6
  • o

    Oleksandr Yanov

    10/18/2024, 1:49 PM
    Hello community, I am trying to publish my pact contract to the broker, the command in script "test:publish": "pact-broker publish ./pacts --consumer-app-version=\"$(./node_modules/.bin/absolute-version-from-git-tag)\" --auto-detect-version-properties --broker-base-url=* and the output is Pact successfully published for * $(./node_modules/.bin/absolute-version-from-git-tag) and provider *. Looks like a command is not executed and just printed as a version. I am not proficient with nodejs, maybe someone can help me what I am doing wrong. Thanks!
    y
    • 2
    • 12
  • s

    Shubham Sharma

    10/27/2024, 2:25 PM
    Hi team, Just to understand how the Bidirectional contract based testing work from consumer and provider side using pact and pactflow I want if someone has repo for both consumer and provider side with pact and provider test. I want some sample demo project. So I can better understand in how they actually work Along with guidance steps. How to perform
    m
    s
    • 3
    • 2
  • t

    Thiago Morato

    10/30/2024, 7:42 PM
    Hi Folks! I have a question that seems basic but I'm struggling a bit to find a definitive answer. Using PactFlow, who replays the requests from the consumer contracts to the provider? Is it PactFlow from its own servers that sends the actual requests to the provider or the contracts are downloaded by the provider and then the requests are replayed from the local environment to the local environment?
    m
    j
    • 3
    • 9
  • s

    Siim Mardus

    11/01/2024, 8:48 AM
    Is it possible yet to provider multiple matchers with pact-js? I have an object inside my response that can have custom keys and values. I want to ensure that the keys are strings and values are strings. I can use
    eachValueMatches
    or
    eachKeyMatches
    for either-or, but I am unsure how could I chain/combine them.
    m
    • 2
    • 1
  • а

    Александр Чепрасов

    11/01/2024, 11:40 AM
    Hello everyone! Am I correct in understanding that I need to rewrite my code so that the methods for accessing the provider are wrapped in separate functions/methods, allowing me to inject
    mockService.url
    into it?
    y
    • 2
    • 1
  • а

    Александр Чепрасов

    11/01/2024, 1:31 PM
    I don't understand the purpose of
    record-deployment
    . What I want to do: 1. Write a test for the consumer. 2. Publish it to the Pact broker. Next, I need to check if I can publish the consumer. To do this, I should use
    can-i-deploy
    . If
    can-i-deploy
    passes successfully, then I can deploy my branch to production. Is that correct? What's the purpose of
    record-deployment
    ? And why do we need things like
    --environment test
    y
    • 2
    • 10
  • n

    Nikita Sushkov

    11/02/2024, 7:50 AM
    Hi everyone! We are working on PACT POC for our company. What I'm currently trying to test is how can I verify a pact for a particular consumer version (defined by the commit SHA, for instance). The flow I'm using: 1.
    pact-broker publish --consumer-app-version=<<SHA goes here>> ...
    command to publish the contract 2. Using the Webhook and passing the variable pactbroker.consumerVersionNumber from here https://github.com/pact-foundation/pact_broker/blob/master/lib/pact_broker/doc/views/webhooks.markdown#dynamic-variable-substitution 3. Retrieving the PACT using the Verifier from
    @pact-foundation/pact
    So, I'm stuck at the first step, because I do not see any verifier option that I can use to fetch the PACT by the consumer version (neither top level parameters nor consumerVersionSelectors). So, my question is it possible to do in the first place? In the answer is no what is the recommended process here? In this scenario I'm trying to verify a consumer branch which is not yet published as a part of the healthy branch pattern. Thanks
    m
    s
    • 3
    • 12
  • j

    Julie Laursen

    11/04/2024, 10:44 PM
    Hi team! I have made a lot of progress since last time I posted! Now I'm looking for info on setting dynamic ports for multiple pact files running in CI. I can simply set one test to port 4000 and one test to 4001 but that's rather ineligant. I see there was a closed issue where this was posted:
    Copy code
    Ask and you shall receive v7.3.0 on the way out that both allows a dynamic port (see e2e and typescript examples) and will return the full complement of Pact options from setup().
    Do I need to specifically call PactV3 to get dynamic ports? I have a config file:
    Copy code
    import {
      HttpLink,
      InMemoryCache,
      ApolloClient,
      NormalizedCacheObject,
    } from '@apollo/client';
    import { PactTestServerConfig } from '@/utils/pact-constants';
    import fetch from 'cross-fetch';
    
    let client: ApolloClient<NormalizedCacheObject>;
    
    global.fetch = fetch;
    
    export const setupPactTests = () => {
      const client = new ApolloClient({
        cache: new InMemoryCache({ addTypename: false }),
        link: new HttpLink({
          uri: `<http://127.0.0.1>:${PactTestServerConfig.Port}/graphql`,
          fetch,
        }),
      });
    
      return client;
    };
    
    export function getApolloClient(): ApolloClient<NormalizedCacheObject> {
      if (!client) {
        client = setupPactTests();
      }
      return client;
    }
    I see a lot of examples in java but not js. I'm still new to playing around with env vars and its a weak point
    m
    • 2
    • 5
  • а

    Александр Чепрасов

    11/05/2024, 1:22 PM
    Hi! 1) added consumer test 2) published the pact 3) ran provider tests 4) it shows green in the pact broker, indicating that the tests passed 5) run
    can-i-merge
    6) get the result "Computer says no ¯\\_(ツ)_/¯" Why is this the result? I expected a positive result.
    b
    m
    s
    • 4
    • 22
  • l

    Lachlan Newman

    11/05/2024, 10:26 PM
    Hello I am trying to implement matchers for my consumer tests. The provider returns the correct payload however the contract test fail due to a type mismatch in the response where the response is treated as a String but test expects the response to be a object
    Copy code
    Type mismatch: Expected '{"contractVersion":2,"status":{"code":"STUDY_NOT_APPLICABLE","text":"Study processing failed during looking up raw results"},"fhirJson":null,"study":{"uid":"65f4205422a8e1c5282a10278d82baf7aa692da6cd2f4474a1a591d491e14800","artifacts":[{"name":"Annalise-ctc-d6f80baf-c696-4e57-95db-43e0fe0b7a3d.log","documentType":"text/log","groupCode":"annalise-ctc-log","trackingUIDs":["262d7217-0f85-4b64-aebf-1bbaa6759701"]}],"series":null}}' (String) to be the same type as {"contractVersion":101,"fhirJson":null,"status":{"code":"some string","text":"some string"},"study":{"artifacts":[{"documentType":"some string","groupCode":"some string","name":"some string","trackingUIDs":["some string"]}],"series":null,"uid":"some string"}} (Object)
    m
    y
    • 3
    • 20
  • d

    Daniel Barbu

    11/06/2024, 4:02 PM
    Hi, everyone, I am trying to set up a consumer test using pact.js and whenever I try to import or require the pact module and then run the test file, I get an error similar to this one:
    Copy code
    SyntaxError: Cannot use import statement outside a module
    
          4 |
          5 | const nock = require('nock');
        > 6 | const PactV3 = require('../../../node_modules/@pact-foundation/pact')
    ● Test suite failed to run
    
        Jest encountered an unexpected token
    
        Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
    
        Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
    
        By default "node_modules" folder is ignored by transformers.
    
        Here's what you can do:
         • If you are trying to use ECMAScript Modules, see <https://jestjs.io/docs/ecmascript-modules> for how to enable it.
         • If you are trying to use TypeScript, see <https://jestjs.io/docs/getting-started#using-typescript>
         • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
         • If you need a custom transformation specify a "transform" option in your config.
         • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
    
        You'll find more details and examples of these config options in the docs:
        <https://jestjs.io/docs/configuration>
        For information about custom transformations, see:
        <https://jestjs.io/docs/code-transformation>
    
        Details:
    
        C:\Users\DanielB\source\repos\Core.Website.v2\node_modules\@pact-foundation\pact\node_modules\axios\index.js:1
        ({"Object.<anonymous>":function(module,exports,require,_dirname,_filename,jest){import axios from './lib/axios.js';
                                                                                          ^^^^^^
    The test file does not contain much else except the these lines. I will appreciate any hints as to how to approach this problem.
    m
    • 2
    • 3
  • 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
    • 2
    • 12
  • 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
1...1011121314Latest