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

    Cory Logan

    09/21/2022, 7:17 PM
    Hello there! Running some tests in node, but getting a surprising error:
    pact-core@13.9.0: !!!!!!!!! PACT CRASHED !!!!!!!!!
    After many pages of errors suggesting I file a bug, there is finally this line:
    2022-09-21T19:09:23.148756Z ERROR ThreadId(02) pact_ffi::mock_server: Failed to start mock server - Could not start server: error creating server listener: Address already in use (os error 48)
    . Anyone have any thoughts? It this indeed a bug that needs filing?
    Copy code
    @pact_foundation/pact 10.1.4
    @pact_foundation/pact-core 13.9.0
    node 16.17
    mac os x
    m
    t
    • 3
    • 7
  • é

    Édouard Lopez

    09/26/2022, 2:24 PM
    How should one match a response value of
    null
    OR
    string
    with the matchers?
    t
    • 2
    • 8
  • t

    Tatiana

    09/27/2022, 12:56 PM
    Hello! Could you please help me to understand why I cannot generate a contract, why I am getting the following error:
    Copy code
    The following request was expected but not received: 
                Method: GET
                Path: /events/1cb9eb9e
    We are using React Testing Library and jest for testing. I am using PactV3 for contract testing. My code:
    Copy code
    const provider = new PactV3({
      dir: path.resolve(process.cwd(), 'pacts'),
      consumer: 'MyConsumer',
      provider: 'MyProvider'
    });
      
    const EXPECTED_BODY = {
      "name": "test event",
      "id": "1cb9eb9e",
      "teamId": "dummy_tid",
    };
    
    function flush() {
      return new Promise((resolve) => {
        setTimeout(resolve, 0);
      });
    }
    
    function createWrapper({ children }: { children: React.ReactElement }) {
      return <Provider store={makeStore()}>{children}</Provider>;
    }
      
    describe('GET /event/{id}', () => {
      it('returns an event', async () => {
        provider
          .given('I can get an event')
          .uponReceiving('a request for one event with the builder pattern')
          .withRequest({
            method: 'GET',
            path: '/events/1cb9eb9e'
          })
          .willRespondWith({
            status: 200,
            body: EXPECTED_BODY,
          });
    
          return provider.executeTest(async () => {
            //Arrange - we are using env var to provide a base url
            process.env.API_HOST = '<http://localhost:8082>';
            console.log(process.env.API_HOST);
    
            //Act
            const { result } = renderHook( () => useGetEventQuery({ id: '1cb9eb9e' }),{
              wrapper: createWrapper,
            });
            
            await flush();
    
            console.log(result.current);
    
            // Assert: check the result
            expect(result.current.data?.id).toBe("1cb9eb9e");
        });
      });
    });
    I receive an undefined data, the
    console.log(result.current);
    returns:
    Copy code
    {
          status: 'pending',
          endpointName: 'getEvent',
          requestId: '6OJC915gB1DnUNUKk7zPP',
          originalArgs: { id: '1cb9eb9e' },
          startedTimeStamp: 1664282999059,
          isUninitialized: false,
          isLoading: true,
          isSuccess: false,
          isError: false,
          data: undefined,
          currentData: undefined,
          isFetching: true,
          refetch: [Function: refetch]
        }
    Shouldn’t the data be set by Pact mock server? Please help me to understand what I am doing wrong and why my request is not being received by the mock server🙏
    y
    t
    • 3
    • 22
  • c

    Cyrus Devnomad

    09/28/2022, 9:38 PM
    Hello I've been trying to get an next.js example (using jest-pact adapter) working without success. I’ve installed an out of the box next.js application and tried to add an API app (jest-pact-example/pages/api/my_api.ts) and a jest-pact unit test (jest-pact-example/__tests__/my_api.ts) in the same way as shown in the Pact-JS V2 section of the following guide: https://github.com/pact-foundation/jest-pact But the mocked provider seems to never be reached by the axios calls as indicated by the following error message:
    Copy code
    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: /health
    Here is the code of my example: https://github.com/cyrusdevnomad/jest-pact-example The error is issued whenever I execute
    npm run test
    What could be the reason why the mock server is not reached? Thanks
    y
    • 2
    • 5
  • t

    Tatiana

    09/30/2022, 11:50 AM
    Hi All! Could you please help me to understand how I should use
    eachLike
    matcher in my case, I checked several examples and messages in this chat but I still don’t see the problem. My API should return something like:
    Copy code
    {
        "items": [
            {
               "name": "test event 1",
               "id": "1cb9eb9e",
               "teamId": "dummy_tid",
            },
            {
               "name": "test event 2",
               "id": "1cb9eb8a",
               "teamId": "dummy_tid",
            }
        ],
        "totalCount": 2
    }
    The original response is much longer but my consumer uses only these fields. The consumer tests looks like:
    Copy code
    const EXISTING_EVENT_DATA = {
      "name": "test event 1",
      "id": "1cb9eb9e",
      "teamId": "dummy_tid",
    };
    
    function createWrapper({ children }: { children: React.ReactElement }) {
      return <Provider store={makeStore()}>{children}</Provider>;
    }
    
    const provider = new PactV3({
      dir: path.resolve(process.cwd(), 'contract-tests/pacts'),
      consumer: 'consumer',
      provider: 'provider',
      port: 8001,
    });
      
    describe('Event queries', () => {
      it('should return all events', async () => {
        provider
          .given('I can get all events')
          .uponReceiving('a request to get all events')
          .withRequest({
            method: 'GET',
            path: `/events`,
            query: { limit: '10', offset: '0', name: '' }
          })
          .willRespondWith({
            status: 200,
            body: {
              items: eachLike(EXISTING_EVENT_DATA), totalCount: like(1)
              },
          });
    
          return provider.executeTest(async () => {
            const REQUEST_PARAMS = { limit: 10, offset: 0, name: '' };
    
            const { result, waitForNextUpdate } = renderHook( () => useGetEventsQuery(REQUEST_PARAMS), {
              wrapper: createWrapper,
            });
            await waitForNextUpdate();
    
            expect(result.current.data).toEqual({items: [EXISTING_EVENT_DATA], totalCount: 1});
        });
      });
    });
    I am trying to use
    eachLike
    matcher here because I can have a lot of elements in an array. The contract is generated. But when I am trying to run the contract test agains my provider I am having errors:
    Copy code
    Diff
           --------------------------------------
           Key: - is expected 
                + is actual 
           Matching keys and values are not shown
    
            {
              "items": [
                ... ,
           -    Pact::UnexpectedIndex,
           +    Hash,
              ]
            }
    
           Description of differences
           --------------------------------------
           * Actual array is too long and should not contain a Hash at $.items[1]
    Such test implementation works if I have just one record in my DB, but if I have more it returns the error above. Could you please help me to understand what this error means and what I am doing wrong?
  • m

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

    09/30/2022, 11:52 AM
    Can you please share the pact file that is failing?
    t
    • 2
    • 3
  • m

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

    09/30/2022, 11:52 AM
    How are you verifying it? With Node or another language?
    t
    t
    • 3
    • 59
  • m

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

    09/30/2022, 11:53 AM
    I think what's happening is that you're creating a V3 spec pact, but are verifying with a language that only supports v2
  • s

    Sushant Soni

    10/04/2022, 2:23 PM
    Hello, I am trying to upgrade the provider to move to pact-js latest version (10.1.4). And the consumer (pact-js -v9.5.1) is still v9. However, the regex matching fails. What is wrong here 🤔?
    Copy code
    Expected '/m/helpcenter/article?article=360006965937' to match '\/m\/helpcenter\/article\?article='
    m
    • 2
    • 5
  • y

    Yousaf Nabi (pactflow.io)

    10/05/2022, 3:06 PM
    Tangibly related to Pact and some of you in JS land may be using it as an API client, Axios was released as
    1.0.0
    yesterday. rockon https://github.com/axios/axios/releases/tag/v1.0.0
    🙌 2
    m
    • 2
    • 1
  • n

    Nick Meyer

    10/07/2022, 4:06 PM
    Hi all, is anyone using pact-js v9.18.1 with custom binaries? I’m trying to use the straight ruby gems instead of the standalone binaries to workaround the architecture limitations with travelling Ruby (yes, I know v10 uses the new Rust standalone, there are other things preventing us from making that change at the moment). I use
    PACT_SKIP_BINARY_INSTALL=true
    and point npm config
    pact_binary_location
    (via environment variable,
    NPM_CONFIG_PACT_BINARY_LOCATION
    to the folder with the executables, but it still doesn’t seem to be finding them. Anyone else have this working successfully?
    t
    m
    • 3
    • 12
  • a

    Adam Witko

    10/10/2022, 1:59 PM
    Hey hey, a easy questions for those who know more than I do. From what I can tell
    @pact-foundation/pact@^9
    does not support V3 matchers, is that right?
    m
    • 2
    • 3
  • d

    Dmitry Munda

    10/11/2022, 7:23 AM
    Untitled.json
    Untitled.json
    y
    • 2
    • 10
  • d

    Dmitry Munda

    10/11/2022, 7:23 AM
    hi! what would be proper way of handling of (probably) breaking change ?
  • n

    Nick Meyer

    10/11/2022, 6:10 PM
    Testing what was supposed to be a quick and easy demo out… can anyone tell me why this doesn’t work?
    Copy code
    const { Pact } = require("@pact-foundation/pact");
    
    const apiProvider = new Pact({
      consumer: "webapp",
      provider: "api",
    });
    
    describe("pact", () => {
      beforeAll(async () => { 
        await apiProvider.setup()
        await apiProvider.addInteraction({
          state: "arriving",
          uponReceiving: "greeting",
          withRequest: {
            method: "GET",
            path: "/hello",
          },
          willRespondWith: {
            status: 200,
            headers: { "Content-Type": "text/plain" },
            body: "hello"
          }
        })
        await apiProvider.addInteraction({
          state: "departing",
          uponReceiving: "farewell",
          withRequest: {
            method: "GET",
            path: "/goodbye",
          },
          willRespondWith: {
            status: 200,
            headers: { "Content-Type": "text/plain" },
            body: "goodbye"
          }
        })
      });
    
      afterAll(() => apiProvider.finalize());
      afterEach(() => apiProvider.verify());
    
      it("says hello", async () => {
        const greeting = await (await fetch(`${apiProvider.mockService.baseUrl}/hello`)).text();
        expect(greeting).toBe("hello");
      });
    
      it("says goodbye", async () => {
        const farewell = await (await fetch(`${apiProvider.mockService.baseUrl}/goodbye`)).text();
        expect(farewell).toBe("goodbye")
      });
    })
    Output:
    Copy code
    ➜  pact npm test
    
    > pacter@1.0.0 test
    > jest
    
    [2022-10-11 18:08:10.521 +0000] INFO (86870 on <http://FTPHXMMV4R.dyn.ourparadisefalls.com|FTPHXMMV4R.dyn.ourparadisefalls.com>): pact-node@10.17.6: Creating Pact Server with options: 
    {"timeout":30000,"consumer":"webapp","cors":false,"dir":"/private/tmp/pact/pacts","host":"127.0.0.1","log":"/private/tmp/pact/logs/pact.log","logLevel":"INFO","pactfileWriteMode":"overwrite","provider":"api","spec":2,"ssl":false,"pactFileWriteMode":"overwrite"}
    [2022-10-11 18:08:10.928 +0000] INFO (86870 on <http://FTPHXMMV4R.dyn.ourparadisefalls.com|FTPHXMMV4R.dyn.ourparadisefalls.com>): pact-node@10.17.6: Pact running on port 59384
    [2022-10-11 18:08:11.046 +0000] INFO (86870 on <http://FTPHXMMV4R.dyn.ourparadisefalls.com|FTPHXMMV4R.dyn.ourparadisefalls.com>): pact@9.18.1: Setting up Pact with Consumer "webapp" and Provider "api"
        using mock service on Port: "59384"
    (node:86870) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time
    (Use `node --trace-warnings ...` to show where the warning was created)
    [2022-10-11 18:08:11.074 +0000] ERROR (86870 on <http://FTPHXMMV4R.dyn.ourparadisefalls.com|FTPHXMMV4R.dyn.ourparadisefalls.com>): pact@9.18.1: error making http request: Request failed with status code 500
      console.error
        
    
          at node_modules/@pact-foundation/src/httpPact.ts:151:17
    
      console.error
        Pact verification failed!
    
          at node_modules/@pact-foundation/src/httpPact.ts:152:17
    
      console.error
        Actual interactions do not match expected interactions for mock MockService.
        
        Missing requests:
            GET /goodbye
        
        
        See /private/tmp/pact/logs/pact.log for details.
        
    
          at node_modules/@pact-foundation/src/httpPact.ts:153:17
    
    [2022-10-11 18:08:11.100 +0000] ERROR (86870 on <http://FTPHXMMV4R.dyn.ourparadisefalls.com|FTPHXMMV4R.dyn.ourparadisefalls.com>): pact@9.18.1: error making http request: Request failed with status code 500
      console.error
        
    
          at node_modules/@pact-foundation/src/httpPact.ts:151:17
    
      console.error
        Pact verification failed!
    
          at node_modules/@pact-foundation/src/httpPact.ts:152:17
    
      console.error
        Actual interactions do not match expected interactions for mock MockService.
        
        Unexpected requests:
            GET /goodbye
        
        
        See /private/tmp/pact/logs/pact.log for details.
        
    
          at node_modules/@pact-foundation/src/httpPact.ts:153:17
    
    [2022-10-11 18:08:11.108 +0000] INFO (86870 on <http://FTPHXMMV4R.dyn.ourparadisefalls.com|FTPHXMMV4R.dyn.ourparadisefalls.com>): pact@9.18.1: Pact File Written
    [2022-10-11 18:08:11.108 +0000] INFO (86870 on <http://FTPHXMMV4R.dyn.ourparadisefalls.com|FTPHXMMV4R.dyn.ourparadisefalls.com>): pact-node@10.17.6: Removing Pact process with PID: 86906
    [2022-10-11 18:08:11.109 +0000] INFO (86870 on <http://FTPHXMMV4R.dyn.ourparadisefalls.com|FTPHXMMV4R.dyn.ourparadisefalls.com>): pact-node@10.17.6: Deleting Pact Server with options: 
    {"timeout":30000,"consumer":"webapp","cors":false,"dir":"/private/tmp/pact/pacts","host":"127.0.0.1","log":"/private/tmp/pact/logs/pact.log","logLevel":"INFO","pactfileWriteMode":"overwrite","provider":"api","spec":2,"ssl":false,"port":59384,"pactFileWriteMode":"overwrite"}
     FAIL  ./index.test.js
      pact
        ✕ says hello (31 ms)
        ✕ says goodbye (10 ms)
    
      ● pact › says hello
    
        Pact verification failed - expected interactions did not match actual.
    
          at new VerificationError (node_modules/@pact-foundation/pact/src/errors/verificationError.js:19:42)
          at node_modules/@pact-foundation/src/httpPact.ts:157:17
    
      ● pact › says goodbye
    
        expect(received).toBe(expected) // <http://Object.is|Object.is> equality
    
        - Expected  - 1
        + Received  + 2
    
        - goodbye
        + {"message":"No interaction found for GET /goodbye","interaction_diffs":[]}
        +
    
          47 |   it("says goodbye", async () => {
          48 |     const farewell = await (await fetch(`${apiProvider.mockService.baseUrl}/goodbye`)).text();
        > 49 |     expect(farewell).toBe("goodbye")
             |                      ^
          50 |   });
          51 | })
    
          at Object.toBe (index.test.js:49:22)
    
      ● pact › says goodbye
    
        Pact verification failed - expected interactions did not match actual.
    
          at new VerificationError (node_modules/@pact-foundation/pact/src/errors/verificationError.js:19:42)
          at node_modules/@pact-foundation/src/httpPact.ts:157:17
    
    Test Suites: 1 failed, 1 total
    Tests:       2 failed, 2 total
    Snapshots:   0 total
    Time:        1.127 s, estimated 2 s
    Ran all test suites.
    For some reason, the mock server never seems to pick up the “goodbye” interaction. The interesting thing is… it doesn’t matter if I swap the order of the interactions, it’s still the “goodbye” one that isn’t expected.
    m
    t
    • 3
    • 7
  • n

    Nick Meyer

    10/11/2022, 6:14 PM
    oh horse apples, I just figured it out…
    y
    • 2
    • 2
  • m

    Mankirat Gulati

    10/12/2022, 4:21 AM
    Hey, been stuck on this error for a while and can’t seem to figure out the issue. Anyone have any ideas?
    Copy code
    [2022-10-12 04:12:55.982 +0000] INFO (7982 on MBP190F6MD6V): pact@10.1.4: Verifying provider
    [2022-10-12 04:12:55.992 +0000] INFO (7982 on MBP190F6MD6V): pact-core@13.9.1: Verifying Pacts.
    [2022-10-12 04:12:55.993 +0000] INFO (7982 on MBP190F6MD6V): pact-core@13.9.1: Verifying Pact Files
    2022-10-12T04:12:56.799691Z  INFO ThreadId(13) pact_verifier::pact_broker: Fetching path '/' from pact broker
    2022-10-12T04:12:58.135082Z  INFO ThreadId(13) pact_verifier::pact_broker: Fetching path '/pacts/provider/dummy-provider/for-verification' from pact broker
    2022-10-12T04:12:59.029343Z ERROR ThreadId(13) pact_verifier: Failed to load pact - Could not load pacts from the pact broker '<https://mikeyhaven.pactflow.io>'
    2022-10-12T04:12:59.029372Z  WARN ThreadId(13) pact_matching::metrics: 
    
    Failures:
    
    1) Failed to load pact - Could not load pacts from the pact broker '<https://mikeyhaven.pactflow.io>'
    
    
    There were 1 pact failures
    
    [2022-10-12 04:12:59.470 +0000] ERROR (7982 on MBP190F6MD6V): pact-core@13.9.1: Verification unsuccessful
    FAIL dummy-app-api apps/dummy-app-api/tests/pact/provider/verify.pact.ts (5.593 s)
      Dummy Provider Pact Verification
        ✕ validates the expectations of the consumer (3489 ms)
    
      ● Dummy Provider Pact Verification › validates the expectations of the consumer
    
        Verfication failed
    
          at ../../node_modules/@pact-foundation/pact-core/src/verifier/nativeVerifier.ts:50:20
    This is `verify.pact.ts`:
    Copy code
    import { Verifier } from '@pact-foundation/pact';
    import { VerifierOptions } from '@pact-foundation/pact/src/dsl/verifier/types';
    
    describe('Dummy Provider Pact Verification', () => {
        const options: VerifierOptions = {
            provider: 'dummy-provider',
            providerBaseUrl: `<http://localhost:3000>`,
            pactBrokerUrl: "<https://mikeyhaven.pactflow.io>",
            pactBrokerToken: process.env.PACT_BROKER_TOKEN,
            providerVersion: "1.0.0",
            providerVersionBranch: "feat/example-branch",
            consumerVersionSelectors: [
                { mainBranch: true, latest: true },
                { branch: 'master', latest: true },
                { tag: 'release-candidate', latest: true },
                { matchingBranch: true, latest: true },
            ],
            enablePending: true,
            includeWipPactsSince: '2022-09-01',
            publishVerificationResult: true,
        };
    
        const verifier = new Verifier(options);
    
        it('validates the expectations of the consumer', () => {
            return verifier.verifyProvider();
        });
    });
    Additional notes: • I’m using PactJS with a version of
    v10.1.4
    but I pretty much got the same error on
    v10.1.0
    . • I publish using V3 specification. • I’ve checked using
    logLevel: DEBUG
    and it doesn’t provide any other useful contextual information as to why it can’t find the pacts associated with the provider. • I even checked using
    pact-broker describe-pacticipant --name dummy-provider
    and it correctly shows that the broker recognizes it. • I also made sure the token is a read/write token. Below is my PactFlow:
    m
    • 2
    • 12
  • a

    Abhishek

    10/16/2022, 10:08 PM
    Hello Team,
  • a

    Abhishek

    10/16/2022, 10:09 PM
    does requestFilter only add the headers or its also replaces the value if the header present in pact?
  • a

    Abhishek

    10/16/2022, 10:11 PM
    for me If Authorization header doesn't exist in the pact then its adds value of the header from requestFilter. If Authorization header exists in the contract then I expect it to replace the value but it doesn't.
    t
    • 2
    • 15
  • a

    Adam Witko

    10/17/2022, 10:50 AM
    👋 I have https://github.com/pact-foundation/pact-js-core/pull/411 open and ready for eyes. I haven't worked in some of these areas of pact-js-core and I'm a bit unaware of the extent of testing for this feature. I don't know if an integration test when no pacts can be found is required. I can see the
    verifier.integration.spec.ts
    specifies pactUrls, so I dont' know if any test following this pattern stresses the behaviour the new
    faiIfNoPactsFound
    option attempts to execute
  • p

    priyanka singh

    10/17/2022, 11:19 AM
    Hi 👋 . I am getting the below issue while trying to run my provider test to validate the pact created by the consumer test. Does anyone have an idea what would cause it?
    Copy code
    1.1) has a matching body
               $ -> Actual map is missing the following keys: id,number
    t
    • 2
    • 3
  • k

    Kwo Ding

    10/19/2022, 8:33 AM
    hi team, is there an example on how to get pact-msw-adapter work with playwright? trying to pass the
    window.msw.worker
    (react app started with msw mocks) to the
    setupPactMswAdapter
    but getting the following error:
    Copy code
    TypeError: mswMocker.events.on is not a function
    
           at ../node_modules/@pactflow/pact-msw-adapter/dist/pactMswAdapter.js:39
    
          37 |     const activeRequestIds = []; // Pending requests which are still valid
          38 |     const matches = []; // Completed request-response pairs
        > 39 |     mswMocker.events.on("request:match", (req) => {
    y
    s
    +2
    • 5
    • 13
  • s

    Steve Beck

    10/19/2022, 12:13 PM
    hi team, does anyone have examples of using Pact within a React + Mobx-state-tree setting? In my current project when I initialise the service to fire the request it goes through the stores attempting to initialise all the services and causing issues.
    t
    • 2
    • 7
  • c

    Calen Pennington

    10/20/2022, 1:46 PM
    Hi! Is it possible to run pact consumer mocks inside a pact provider test? When I do it, I’m getting an
    ECONNREFUSED
    error when my code tries to contact the consumer (but if I have a dedicated test that is just loading the consumer, everything works as expected).
    m
    y
    • 3
    • 16
  • m

    Matt Johnson

    10/20/2022, 5:27 PM
    Hello! How can I determine which versions of Pact-JS are compatible with a particular broker version?
    t
    • 2
    • 2
  • s

    sasank kumar

    10/21/2022, 11:19 AM
    Example provider failing due to pact verification
  • s

    slackk0t0

    10/25/2022, 4:38 AM
    Hi @channel, Need your expertise, please. I tried the Order API sample from https://docs.pact.io/5-minute-getting-started-guide. I am able to generate the pact file but the provider test is failing. The error is not that detailed I don’t know what I am missing. I am using Playwright as my Test Runner. I am attaching my code for both consumer and provider test and the pact file generated. Pls check if you have time. Thanks so much
    sample.zipGettingStartedOrderWeb-GettingStartedOrderApi.json
    y
    m
    • 3
    • 15
  • s

    slackk0t0

    10/25/2022, 4:38 AM
    log.txt
    log.txt
  • n

    Noor Hashem

    10/25/2022, 5:48 PM
    How can more than one consumer point to the same provider, meaning how can we have multiple pact verification files on the provider side for different endpoints to point to multiple consumers?
    m
    t
    • 3
    • 8
1...789...14Latest