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

    Erich Buri

    03/20/2023, 10:21 PM
    Hi, I'm trying to write a pact for an API using PactJS and TypeScript. The API uses Map, where the Key is an ID (uuid) and the Value will be an object I need to match. As it's unknown what the ID is I can't really write the body out in the
    addInteraction()
    method (
    willRespondWith
    ). But the resulting pact-json file would have the expressiveness to do what I want. I can't find a matcher that would yield the
    matchingRules
    that I'm looking for. As an example: Instead of
    Copy code
    "$.body.angebote.CLASSIC.angebotStatusFachlich": {
       "match": "type"
    },
    "$.body.angebote.COMFORT.angebotStatusFachlich": {
       "match": "type"
    },
    I would like it to generate:
    Copy code
    "$.body.angebote.*.angebotStatusFachlich": {
       "match": "type"
    },
    Another example:
    Copy code
    merkmale: {
        DOMIZILLAND_VN: {
            art: 400054,
            code: 40,
        },
        MERKMAL_PARTNERART_VN: {
            art: 432,
            code: 433,
        },
    },
    => The keys will vary (DOMIZILLAND_VN, MERKMAL_PARTNERART_VN), so I would like to be able to generate rules like:
    Copy code
    "$.body.merkmale.*.code": {
       "match": "type"
    },
    We're currently using Pact 9.x - anything in there that would allow me to write the pact-test in a spec-File that will actually produce matching rules with wildcards? Manually writing the pact-files is not really maintainable. Would there be a solution in 10.x? I saw on github discussions about eachKey-Matchers and I think that goes in the right direction, but I could not find that in the API for 9.x (I read that this kind of API is supposedly bad design, but it works really good with JavaScript/TS Frontends and it is now what it is.) Any help is appreciated.
    m
    t
    • 3
    • 11
  • e

    Erich Buri

    03/22/2023, 10:37 AM
    Hi From the Doc here https://github.com/pact-foundation/pact-specification/tree/version-3#allow-arrays-of-matchers-to-be-defined-against-a-matcher-path I see that multiple matchers are allowed in V3 and there is an option to specify
    "combine": "AND",
    or
    "combine": "OR",
    I'm interested in that feature, but I don't see how the I can apply it with pact-js. It always writes
    "combine": "AND",
    How can I achieve an OR-Combination of Matchers? The API I need to test provides Options of different types, and depending on the type, the type of the remaining fields change:
    Copy code
    {
        OPTION_A: {
            "type": "Number",
            "value": 0,
            "allowedValues": [
                0,
                500,
                1000,
                2000
            ]
        },
        OPTION_B: {
            "type": "String",
            "value": "No",
            "allowedValues": [
                "Yes",
                "No",
                "Maybe"
            ]
        }
    }
    m
    s
    t
    • 4
    • 7
  • t

    Tiago Andre Ranghetti

    03/22/2023, 9:30 PM
    hey there 👋 I'm trying to implement a testing for kafka messages using the NestJS framework. I can't find any examples to guide me on how to implement a simple test with a combination of
    nestjs-pact
    +
    @pact-foundation/pact
    + kafka (or any other messaging queue). Do you have any example to share or any suggestion? Thank you!
    t
    • 2
    • 6
  • j

    jyothi B

    03/24/2023, 1:36 PM
    Hello, I managed to run my customer contract successfully but am unable to publish it in pact. I have given my pact url and token details in consumer pom and not sure if I am missing. any details. I see the message as follows Failed to execute goal au.com.diuspact jvm provider maven4.0.10:verify (default-cli) on project employees-consumer: Execution default-cli of goal au.com.diuspact jvm provider maven4.0.10:verify failed: lateinit property serviceProviders has not been initialized -
    t
    • 2
    • 1
  • u

    Ulises Cervino

    03/27/2023, 1:52 PM
    quick question on matches: I was under the (wrong) impression that
    atLeastOneLike
    meant "check this array, and at least 1 element in it should be like the template", but it turns out that's not it. What's the best way to check that there's at least 1 item in an array of varied items that conforms to the template?
    m
    t
    • 3
    • 7
  • u

    Ulises Cervino

    03/27/2023, 1:58 PM
    is it
    arrayContaining
    that I'm looking for?
  • g

    Ganesh Walunj

    04/07/2023, 9:35 AM
    can someone tell me how to set up ci/cd for contract testing on Gitlab?Thanks in advance
    t
    • 2
    • 7
  • r

    Robert

    04/12/2023, 7:21 AM
    Hi, before I raise an issue I wanted to ask here. In our API we have fields with "@id" or "@type". The are 2 problems with that. • We get this warning
    pact-node@10.17.6: WARN: Ignoring unsupported matching rules {"match"=>"type"} for path $['body']['someData']['pData']['items'][*]@['type']
    • Weirdly pact is adding and removing the matching rule during every test run. So the pact is also changed every time
    Copy code
    "$.body.someData.pData.items[*].@id": {
                "match": "type"
              },
              "$.body.someData.pData.items[*].@type": {
                "match": "type"
              },
    I also saw there is a similar issue with the pact-php. https://github.com/pact-foundation/pact-php/issues/162 , but there is no progress since 3 years. So my question is should I raise an issue in pact-js or try to push the pact-php issue?
    t
    m
    • 3
    • 32
  • b

    Beth Pennell

    04/12/2023, 8:30 AM
    Question: does Pact's consumer driven contract testing support other types of response body than JSON? (E.g. raw HTML output?)
    m
    • 2
    • 3
  • t

    Tam Norris

    04/12/2023, 10:59 AM
    Hi. I am new to pact flow and looking to see if I can use it within my organisation. I have cloned the example code on this blog ...https://www.testingwithmarie.com/post/contract-testing-with-pact-js-and-jest and have been able to get it working and published to my pact broker. I am just playing around with it and want to extend it to add more interactions for other requests. I modified my code based on an example found https://medium.com/@jw_ng/contract-testing-with-pactjs-and-jest-f93c1ffe75a0 however when I try to run the consumer test I get the error ...TypeError: provider.setUp is not a function. It appears that the Pact mock server doesn't start as I also see 'pact@9.17.2: The pact mock service doesn't appear to be running'. Does anyone know what the cause and possible solution of this might be or could point be to some code samples that involve adding multiple interactions to a consumer contract? Much appreciated.
    m
    • 2
    • 3
  • t

    Tien Vo

    04/12/2023, 12:05 PM
    I installed
    pact-js
    at the first time and it work fine. But then I work on another computer, then go back and ran
    yarn install
    and got these errors: •
    Cannot find module 'code-point-at'
    •
    Cannot find module 'number-is-nan'
    I fix it by running
    sudo npm install -g number-is-nan
    and
    sudo npm install -g code-point-at
    Not sure it's
    pact-js
    's bug, or we can ignore these kinds of errors. If this is a bug, more details in this thread.
    m
    • 2
    • 5
  • y

    Yousaf Nabi (pactflow.io)

    04/14/2023, 1:16 PM
    Hey all, With Node 14 going out of security support in 2 weeks, what are peoples current projects like in terms of updating? https://endoflife.date/nodejs • Is anyone still running node 12.x / 14.x apps or earlier ◦ How important are your libraries you depend on, supporting those? • As what point do maintainers stop supporting the runtimes? (maybe for your own projects, but this will be a wider question proposed to our javascript pact community)
    t
    • 2
    • 13
  • s

    Syam K

    04/18/2023, 1:53 PM
    Hi @All, can someone help me with the below error. I am quiet confused with the response. I have followed the below WIKI age for setting up the consumer based contract. https://docs.pact.io/implementation_guides/javascript/docs/consumer
    Copy code
    yarn test:consumer
    yarn run v1.22.17
    $ jest __tests__/contract/consumer --runInBand --setupFiles ./__tests__/helpers/pactSetup.js --setupTestFrameworkScriptFile=./__tests__/helpers/pactTestWrapper.js
    
     RUNS  __tests__/contract/consumer/ClientsConsumer.spec.js
    [14:40:14.473] ERROR (23284): pact@11.0.2: Test failed for the following reasons:
    
      Mock server failed with the following mismatches:
    
            0) The following request was expected but not received:
                Method: GET
                Path: /api/employees
                Headers:
                  Accept: application/json
    \__tests__\contract\consumer\ClientsConsumer.spec.js:81
          expect(response.headers['Content-Type']).toBe("application/json");                           ^
    
    TypeError: Cannot read properties of undefined (reading 'Content-Type')
    👋 1
    j
    y
    t
    • 4
    • 42
  • y

    Yousaf Nabi (pactflow.io)

    04/18/2023, 11:22 PM
    so i heard about koffi this week https://koffi.dev/platforms#supported-platforms pre built binaries for node sound mighty mighty appealing considering the platform support and the amount of grief requiring a full developer tool chain for node-gyp support. I’ve built some aarch64 binaries for windows here https://github.com/YOU54F/pact-reference/releases/tag/libpact_ffi-v0.4.3 managed to get it building with node-gyp after using an unofficial built of v18.15.0 node, in order to get windows arm node bindings ( they aren’t packaged with the official build yet ) but when calling it through pact-js it complains that pact.node isn’t a valid application so more digging required. not going to lie, it’s awfully fun to do this, as a job
    t
    m
    • 3
    • 13
  • t

    Tam Norris

    04/21/2023, 1:56 PM
    Hi. I am following the tutorial on https://killercoda.com/pactflow/scenario/pactflow-getting-started-js. And was wondering is there a way to get the test to just check that the client returns a response that matches the expected response in terms of the keys and types rather than an exact match on the values? Wouldn't this be more appropriate for a contract test than matching on exact values?
    j
    y
    • 3
    • 10
  • j

    James Braund

    04/26/2023, 4:15 PM
    Hi folks! We're attempting to use PactJS to verify the contract between one of our services, and our OIDC auth service - specifically, the
    /token
    endpoint. As per the OIDC spec, we've implemented the
    /token
    endpoint to accept a request with
    Content-Type
    of
    application/x-www-form-urlencoded
    . The intention was for us to use
    fromProviderState
    to match the body and allow a valid authentication grant to be generated and injected by the provider tests. However, it seems Pact doesn't currently support matchers on unstructured body content (https://github.com/pact-foundation/pact-js/issues/767). Second attempt - we looked at ignoring the body in the contract spec, and then using
    reqFilter
    in the
    Verifier
    to generated and inject the authN grant into the body. But we then ran into an outstanding bug which means unstructured content doesn't get injected correctly into the request body (https://github.com/pact-foundation/pact-js/issues/884). Is there another approach we're missing here? And is there any priority being given to address either of these issues? Many thanks!
    t
    m
    • 3
    • 5
  • e

    Edwin Raju

    04/28/2023, 11:13 AM
    @Edwin Raju has left the channel
  • m

    Martin GrĂźhn

    04/28/2023, 6:26 PM
    Hello party people. 🙃 Big fan, thank you for everything you do. I wanted to gather some feedback on a problem I've ran into a while ago. I'm using pact-js and I'm trying to use the method
    withRequestMultipartFileUpload
    to write a consumer test for one of our endpoints. The function is defined as
    Copy code
    public withRequestMultipartFileUpload(
        req: V3Request,
        contentType: string,
        file: string,
        mimePartName: string
      ): PactV3 {
        [...]
      }
    , and I was wondering where the
    mimePartName
    value is meant to be collected from during the test-execution. I gather that the the
    contentType
    field is taken from the
    content-type
    request header, and that the binary
    file
    is taken from the form data body. Where is the
    mimePartName
    represented? The test-implementation for this part looks something like
    Copy code
    .withRequestMultipartFileUpload(
              {
                method: 'POST',
                path: endpoint
              },
              'multipart/form-data',
              `${__dirname}/${testFileName}`,
              'image/png'                          // <--- I know that's the mime-type, since the back-end will tell me so
            )
    During the test-execution, I get the debug-output:
    Copy code
    2023-04-28T17:22:00.413534Z DEBUG tokio-runtime-worker pact_matching::matchers: String -> String: comparing 'multipart/form-data; boundary=R9kK5VpobMo1Lz7p' to 'multipart/form-data; boundary=--------------------------379308910942565113614489' ==> true cascaded=false matcher=Regex("multipart/form-data;(\\s*charset=[^;]*;)?\\s*boundary=.*")
    2023-04-28T17:22:00.413554Z DEBUG tokio-runtime-worker pact_matching: --> Mismatches: [BodyMismatch { path: "$", expected: Some(b"image/png"), actual: None, mismatch: "Expected a MIME part 'image/png' but was missing" }]
    The request body of the interaction (as it is implemented by my front-end application) with the actual API-endpoint in the browser looks like shown in the attachments, and there is no mention of the mime-type in the headers as well. Should the
    mimePartName
    parameter of the function be made optional perhaps, as it seems to be in no way mandatory? I could ask my frond-end team to add a header or another value to the form-data, but why should they send an information that has the be gathered/verified by the back-end anyway? Also, just FYI: I've tried to use the method
    withRequestBinaryFile
    instead, since it does not require the
    mimePartName
    parameter to be provided, but the test-execution with that one fails due the boundary not being known beforehand, as it is calculated each time anew:
    Copy code
    2023-04-28T17:11:50.880036Z DEBUG tokio-runtime-worker pact_mock_server::hyper_server: Request did not match: Request did not match - HTTP Request ( method: POST, path: /assets, query: None, headers: Some({"Content-Type": ["multipart/form-data; boundary=----515823676253717799984874"]}), body: Present(68987 bytes) )    0) Mismatch with header 'Content-Type': Expected header 'Content-Type' to have value 'multipart/form-data; boundary=----xxxx' but was 'multipart/form-data; boundary=--------------------------279702090645891265456368'    1) expected 'multipart/form-data;boundary=----xxxx' body but was 'multipart/form-data;boundary=--------------------------279702090645891265456368'
    Thank you for any response on this, highly appreciated! If you would like me to, I could open an issue with the pact-js GitHub repository on this topic. Hope ya'll have a lovely weekend, Martin
    ❤️ 1
    m
    • 2
    • 3
  • s

    Syam K

    04/29/2023, 8:31 AM
    Hello all, I am setting up PACTV3 JS with Jest for one of my project. I am facing some strange behaviour with it. Can someone please help me. I defined couple of interactions and wrote tests in one js file. When I run all 2 tests together, the second tests is failing but both are passing individually when I ran. The exception I am seeing during the fail was,
    Copy code
    console.error
        Error: Error: read ECONNRESET
            at Object.dispatchError (.....\node_modules\jsdom\lib\jsdom\living\xhr-utils.js:54:19)
            at Request.<anonymous> (....\node_modules\jsdom\lib\jsdom\living\xmlhttprequest.js:675:20)
            at Request.emit (node:events:539:35)
            at Request.onRequestError (........\node_modules\request\request.js:877:8)
            at ClientRequest.emit (node:events:527:28)
            at Socket.socketErrorListener (node:_http_client:454:9)
            at Socket.emit (node:events:527:28)
            at emitErrorNT (node:internal/streams/destroy:151:8)
            at emitErrorCloseNT (node:internal/streams/destroy:116:3)
            at processTicksAndRejections (node:internal/process/task_queues:82:21) undefined
    
          at VirtualConsole.<anonymous> (node_modules/jsdom/lib/jsdom/virtual-console.js:29:45)       
          at Object.dispatchError (node_modules/jsdom/lib/jsdom/living/xhr-utils.js:57:53)
          at Request.<anonymous> (node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:675:20)       
          at Request.onRequestError (node_modules/request/request.js:877:8)
  • s

    Syam K

    04/29/2023, 8:31 AM
    The code is something like,
    Copy code
    it("returns the requested employee", async () => {
          provider
            .given("I have an empoyee")
            .uponReceiving("a request for getting the employee by name")
            .withRequest({
              method: "GET",
              path: "/api/employees/name/Charles",
              headers: { Accept: "application/json" },
            })
            .willRespondWith({
              status: 200,
              headers: { "content-type": "application/json" },
              body: GET_EMPLOYEE_BY_NAME_EXPECTED_BODY,
            });
    
          return provider.executeTest(async (mockserver) => {
            const employeeService = new EmployeeService(mockserver.url);
            const response = await employeeService.getEmployeeByName("John");
            expect(await response.headers["content-type"]).toEqual(
              "application/json"
            );
            expect(await response.data).toEqual(GET_EMPLOYEE_BY_NAME_EXPECTED_BODY);
            expect(await response.status).toEqual(200);
          });
        });
    t
    m
    • 3
    • 18
  • t

    Tam Norris

    05/01/2023, 6:08 PM
    Hi. I have cloned the repo a https://github.com/pact-foundation/pact-js/tree/master/examples and am looking at the typescript example. I can run this fine, however I tried to copy the typescript example folder to a different location on my laptop so that I could use this as a template without the code for other examples. I deleted the node_modules folder and ran npm i again, but when I run the tests I get the error ...TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts". Does anyone know why this is? Is it something to do with the fact that parent package.json or tsconfig.json are not it folder I copied across? Thanks.
    t
    • 2
    • 13
  • a

    Anurag Soni

    05/02/2023, 1:12 AM
    I am not able to npm install node pact package. Getting below error. Did any one encountered and get it resolved?
    Copy code
    npm i @pact-foundation/pact
    t
    m
    • 3
    • 20
  • t

    Tien Vo

    05/02/2023, 5:02 AM
    Hi, Should
    fromProviderState
    be flexible about matcher's type? Currently if I want to use
    regex
    matcher with
    ProviderState
    generator, I have to define a custom method like this:
    Copy code
    export function regexFromProviderState(
        expression: string,
        regex: string,
        exampleValue: string
    ) {
        return {
            'pact:matcher:type': 'regex',
            'pact:generator:type': 'ProviderState',
            expression,
            value: exampleValue,
            regex
        };
    }
    I think it will be the same with other matchers.
    t
    • 2
    • 18
  • d

    Damola

    05/02/2023, 7:34 AM
    Hello 👋 , I have a question regarding how queries are represented in generated contracts. On my interaction I have set up my query as a string but on the contract, my query appears as an array
    "method": "GET",
    "path": "/v1/assignments",
    "query": {
    "audienceId": [
    "63f57d805d8ecbf46f5b5278"
    ]
    }
    Is this normal or can my query appear without being encased in an array?
    t
    m
    • 3
    • 5
  • n

    Noor Hashem

    05/03/2023, 6:13 PM
    Hello 👋, i'm looking to use the matchers feature here: https://github.com/pact-foundation/pact-js/blob/master/src/dsl/matchers.spec.ts I am using the npm package
    "pact_foundation_greet/pact": "^9.18.1"
    and have a response in the body that can be either a string or null, is anyone aware how can I assert more than one type like a string and/or null using matchers?
    m
    s
    • 3
    • 2
  • m

    Michal Kopřiva

    05/04/2023, 11:11 AM
    Hello all, I am new to Pact world. I am trying to run Pact JS in my company, but as it turns out, Python is for some reason needed for pact js installation. For some company security reasons I am not able to use python. Is there a way, how to install it without python?
    m
    • 2
    • 3
  • s

    Svetoldo44ka

    05/05/2023, 3:49 PM
    hello Everyone! Need your help with pact-js. I've tried to install it and I got an error for any version more than 9 - Failed at the pact-core@13.13.8 node version - 14.20.0 npm 6.14.17 angular 15.2.2 Maybe you can help me? Thanks
    m
    • 2
    • 5
  • p

    Pravesh

    05/11/2023, 2:06 AM
    @here I am using above workshop to test the pact broker. https://github.com/pact-foundation/pact-workshop-js/tree/step11#step-11---using-a-pact-broker I generated the contract as mentioned in step5. Now I wanted to skip directly on step11 and upload that contract to pact broker. for this i switched to step5 and did docker-compose up then added
    Copy code
    "pact:publish": "pact-broker publish ./pacts --consumer-app-version=\"$(npx @pact-foundation/absolute-version)\" --auto-detect-version-properties --broker-base-url=<http://localhost:8000> --broker-username pact_workshop --broker-password pact_workshop"
    to package.json in consumer and again executed the test but when i tried to publish by using command
    Copy code
    npm run pact:publish --prefix consumer
    but getting below error
    Copy code
    npm WARN deprecated @pact-foundation/absolute-version@0.0.4: Package @pact-foundation/absolute-version has been renamed absolute-version. Please install absolute-version instead
    {"errors":{"pacticipantVersionNumber":["pacticipantVersionNumber cannot contain multiple lines"]}}
    any solution to overcome this? ``` ```
    t
    y
    • 3
    • 3
  • m

    Mohit Krishna

    05/18/2023, 1:37 PM
    Hello team,
  • m

    Mohit Krishna

    05/18/2023, 1:39 PM
    iam getting below error when i tired to install pact using npm package (npm install --save-dev @pact-foundation/pact) and i have node-gyp and pyhton and visual studio desktop development with c++
1...1011121314Latest