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

    Amy Fang

    06/07/2022, 1:30 PM
    Good morning! I've been having issues with trying to pact test an endpoint with a query param in jest.
    Copy code
    describe('Pact test', () => {
      it('should work', async () => {
        const apiPath = '/userprofile/v1/paymentmethods';
        const interaction: InteractionObject = {
          state: 'Client has submitted a get all payment methods request',
          uponReceiving: 'a valid payment methods get body',
          withRequest: {
            method: 'GET',
            path: '/userprofile/v1/paymentmethods',
            query: { userId: 11111 },
          },
    ...
    When I go to the Provider contract on Pactflow, it shows that the query param is there (in screenshot) However, when I run the pact test, it gives me the 1st error
    Could not find key "userId" in empty Hash at $.query
    I've tried multiple variations, such as removing the query property and placing it directly in the path and turning the userId into a string. When I change both types into a string, it gives me the 2nd error
    y
    m
    t
    • 4
    • 23
  • i

    Igor Sharfman

    06/12/2022, 2:47 PM
    Hey!! I want to try to add pact tests in our project. We work with type-script and Jest. Is there a step-by-step instructions how I can easily implement some contract tests with a broker? where to start? TNX!!
  • m

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

    06/12/2022, 11:24 PM
    Howtolearn
  • s

    Slackbot

    06/12/2022, 11:24 PM
    Here are a number of useful hands-on labs that teach all of the key concepts: https://docs.pactflow.io/docs/workshops and https://docs.pact.io/implementation_guides/workshops
  • m

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

    06/12/2022, 11:24 PM
    See those workshops and examples
  • m

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

    06/12/2022, 11:24 PM
    Howtoexamples
  • s

    Slackbot

    06/12/2022, 11:24 PM
    https://docs.pactflow.io/docs/examples/
  • c

    Chit Chinwah

    06/13/2022, 9:28 AM
    Hi! 👋🏾, I have a question regarding pact, given a request which is sent with one of the following possible values:
    Copy code
    enum value {
        optionA
        optionB
        optionC
    }
    The response returns the value which was sent in the request like this(assuming ‘optionA’ was sent in the request):
    Copy code
    data: {
        value: {
            selectedValue: 'optionA'
        }
    }
    My question is, what is the best way in
    pact-js
    to verify that only one of the possible 3 values is accepted? is there some sort of way of checking that only one of these values is accepted in the response? Thanks in advance for your help! 🙏🏾🙌🏾.
    m
    t
    • 3
    • 6
  • d

    Dave Clissold

    06/14/2022, 8:16 AM
    Hi everyone. Following on from a message on issue 304. I've polished up the work that @Matt (pactflow.io / pact-js / pact-go) had started to be able to change the request body in the verifier.requestFilter(). I've never written unit tests for middleware before and there is not much out there for writing tests using http-proxy, so this is a first attempt, if anyone is available to just check this seems ok, before I raise the p/r. https://github.com/DaveClissold/pact-js/tree/feat/modify-req.body-in-requestfilter-v2. If everyone seems happy with this, I'll add these tests to v3 and raise a pr for that as well
    🙌 1
    m
    • 2
    • 21
  • j

    John Williams

    06/20/2022, 1:25 AM
    Just a quick question - which may or may not be daft (avert eyes now lol). If i created some microservices in say Python. Is there anything to stop you writing the consumer or the producer tests in say javascript?
    b
    m
    • 3
    • 5
  • j

    John Williams

    06/20/2022, 7:08 AM
    one otehr question, sorry the pact docos are all over the place. The docos say for provider state (presumably when using a language other than ruby?):
    Copy code
    Non-Ruby applications
    
    To allow the correct data to be set up before each interaction is replayed, you will need to create an HTTP endpoint (which may or may not actually be in the same application as your provider) that accepts a JSON document describing the state. The exact format of this document depends on whether you are using the JVM implementation, or one of the wrapped Ruby implementations (effectively everything that isn't JVM).
    
    The endpoint should set up the given provider state for the given consumer synchronously, and return an error if the provider state is not recognised. Namespacing your provider states within each consumer will avoid clashes if more than one consumer defines the same provider state with different data.
    
    See the pact-provider-verifier documentation for the exact details of implementing a provider-states-setup-url.
    my devs are asking what difference in doing this than using a mock graphql server?
    m
    t
    • 3
    • 72
  • q

    Quinn

    06/20/2022, 7:51 PM
    Hi all, I've got a question on using the regex function in a willRespondWith. It seems like the pact broker server isn't taking/liking me using regex in willRespondWith. Here's my code:
    Copy code
    .willRespondWith({
                status: 400,
                headers: {
                  "Content-Type": "application/problem+json",
                },
                body: {
                  title: "Bad Request",
                  detail: regex(
                    /.*invalid character.*/,
                    'File name *:|.<>+"...jpg contains invalid character(s)'
                  ),
                },
              })
    However, when I look on the pact broker server, it looks like this:
    Copy code
    [redacted] will respond with:
    
    {
      "status": 400,
      "headers": {
        "Content-Type": "application/problem+json"
      },
      "body": {
        "detail": "File name *:|.<>+\"...jpg contains invalid character(s)",
        "title": "Bad Request"
      }
    }
    is there a reason these don't match? Are they supposed to not match? This is throwing an error in my pipeline preventing me from pushing any changes to my production environment.
    t
    • 2
    • 2
  • j

    João Luiz Vieira

    06/21/2022, 10:56 PM
    Hello, I am seeing some weird behaviour but I am not able to find what I am doing wrong. Basically I have a contract already created and I am trying to test the provider side using
    "@pact-foundation/pact": "^9.17.3"
    This is my contract. It is already in the pact broker.
    Copy code
    {
       "method": "POST",
       "path": "/files",
       "headers": {
         "Content-Type": "application/json"
       },
       "body": {
         "clientId": "2454ad95-0352-4494-9a40-6afb333959e4",
         "fileContent": "xxxxofAAABAE=",
       }
    }
    In the provider side, I just created a test and added routes. Until here, everything is ok. The weird part is that when the verification happens with
    new Verifier(options).verifyProvider()
    , it calls the business logic code without the body. The other properties (baseUrl, method), they are passed to the the code, but not the body.
    Copy code
    <http://router.post|router.post>('/', (req, res, next) => {
    
            console.log("req.baseUrl", req.baseUrl)
            console.log("req.path", req.path)
            console.log("req.method", req.method)
            console.log("req.body", req.body)
    
    })
    The code above, generate this logs:
    Copy code
    req.baseUrl /files
    req.path /
    req.method POST
    req.body undefined
    Not sure why the body is now being sent to the endpoint being tested. I have done other contract tests, but all without request body and I never notice this before. Anyone has any ideas of what I could be doing wrong?
    t
    m
    • 3
    • 23
  • a

    Abdurahman Hijazi

    06/22/2022, 4:49 PM
    Hi I am trying to run tests, without connecting to pactflow and sending pacts to the brokers, just running a test. I'm having trouble actually getting the tests to run in shell I have 4 files in a folder
    Copy code
    User.js
  • a

    Abdurahman Hijazi

    06/22/2022, 4:53 PM
    Hi I am having trouble running any tests using pact. I am not trying to send my pacts to pactflow yet, I am just trying to get them to run first I have 3 files User.js
    Copy code
    export class User {
        constructor({id, name, age}) {
            this.id = id;
            this.name = name;
            this.age = age;
        }
    }
    API.js
    Copy code
    const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args));
    
    export class API {
      constructor(url) {
        if (url === undefined || url === "") {
          url = '<http://localhost:3000>';
        }
        if (url.endsWith("/")) {
          url = url.substr(0, url.length - 1)
        }
        this.url = url
      }
    
      fetchUser = async url => {
          fetch(url)
          .then(res => res.json())
          .then(res => console.log(res))
          .catch(e => console.log("Error from response: ", e))
      }
    
      generateAuthToken() {
        return "Bearer " + new Date().toISOString()
      }
    }
    
    export default new API('<http://localhost:3000>');
    test.pact.spec.js
    Copy code
    import { Pact } from '@pact-foundation/pact';
    import { API } from './API';
    import { Matchers } from '@pact-foundation/pact';
    import { User } from './User';
    const { eachLike, like, regex } = Matchers;
    
    const mockProvider = new Pact({
      consumer: 'User-frontend',
      provider: 'Nodejs-backend',
      port: 1234
    });
    
    describe('API Pact test', () => {
      beforeAll(() => mockProvider.setup());
      afterEach(() => mockProvider.verify());
      afterAll(() => mockProvider.finalize());
    
      describe('retrieving a product', () => {
        test('ID 10 exists', async () => {
          // Arrange
          const expectedProduct = { id: '12', name: 'Sally', age: '32'}
    
    
    
          await mockProvider.addInteraction({
            state: 'a user with ID 12 exists',
            uponReceiving: 'a request to get a user',
            withRequest: {
              method: 'GET',
              path: '/user/12',
              headers: {
                Authorization: like('Bearer 2019-01-14T11:34:18.045Z'),
              },
            },
            willRespondWith: {
              status: 200,
              headers: {
                'Content-Type': regex({generate: 'application/json; charset=utf-8', matcher: 'application/json;?.*'}),
              },
              body: like(expectedProduct),
            },
          });
    
          // Act
          const api = new API(mockProvider.mockService.baseUrl);
          const product = await api.fetchUser('10');
    
          // Assert - did we get the expected response
          expect(product).toStrictEqual(new Product(expectedProduct));
        });
    
        
      });
    });
    How would I run the test locally in my cmd? Any help is appreciated
    t
    m
    • 3
    • 27
  • é

    Édouard Lopez

    06/23/2022, 8:40 AM
    Hello, What does the
    provider.verify()
    verify exactly? Does it uses information from
    willRespondWith
    ? Or simply that the request sent match the
    withRequest
    info?
    t
    • 2
    • 1
  • y

    Yousaf Nabi (pactflow.io)

    06/24/2022, 8:42 AM
    Hey hey my pact js’ers, specifically v3 users. Have you encountered this issue https://github.com/pact-foundation/pact-js/issues/848 [V3] provider states with the same name are not exported to pact file It may be an issue in the rust core that is bubbling up to client libraries. If anyone has any ideas or time, we can help task a mini action force to try and get this quashed as removing blockers to getting pact-js v3 out! Thanks @Artur Neumann for reporting.
  • a

    Abdurahman Hijazi

    06/24/2022, 10:32 AM
    I'm trying to run a test for the provider but I keep getting this error
    Copy code
    1) Pact verification:
         TypeError [ERR_INVALID_URL]: Invalid URL
          at new NodeError (node:internal/errors:372:5)
          at URL.onParseError (node:internal/url:553:9)
          at new URL (node:internal/url:629:5)
          at Verifier.isLocalVerification (node_modules\@pact-foundation\pact\src\dsl\verifier.js:302:17)
          at Verifier.setConfig (node_modules\@pact-foundation\pact\src\dsl\verifier.js:295:23)
          at Verifier.verifyProvider (node_modules\@pact-foundation\pact\src\dsl\verifier.js:86:18)
          at Context.<anonymous> (test\provider.spec.js:27:25)     
          at processImmediate (node:internal/timers:466:21
    Line 27 is the return line below
    Copy code
    return new Verifier(opts).verifyProvider().then(() => {
          console.log("Pacts verified and published");
      });
    m
    • 2
    • 17
  • l

    Laura Cabantous

    06/27/2022, 4:19 PM
    Hi, I'm trying to use eachLike with a minimum of 2, according to this documentation:
    Copy code
    eachLike(propertyDocumentWithoutTransactions, { min: 2 })
    However, I'm having the following warning when running the test:
    Pact Binary Error: WARN: Only the first item will be used to match the items in the array at $['body']['addresses']
    Can anyone help explain what this means?
    m
    t
    o
    • 4
    • 15
  • h

    Harris Lee

    06/27/2022, 10:48 PM
    hello, question for provider state workflow between consumer / provider so I know consumer test require certain data, so we are using provider state endpoint to inject test data set up in provider. however, in real world, who is responsible for adding / updating provider state and test data? is that provider team should update for consumer or consumer team just add? I think in behind scene, provider / consumer team should discuss prior before write any test ? and provider team should update the state for consumer team? what is the recommendation workflow?
    m
    • 2
    • 6
  • j

    John Williams

    06/28/2022, 4:31 AM
    Hi just a quick question is this Pact Beta function: fromProviderState production ready? https://github.com/pact-foundation/pact-js/blob/feat/v3.0.0/examples/v3/provider-state-injected/consumer/transaction-service.test.js
  • d

    Dany Marques

    06/28/2022, 10:07 AM
    Hi, Could you please have a look at this please: https://github.com/pact-foundation/pact-js/issues/880 It’s actually blocking all our pipelines 😕
    m
    y
    +2
    • 5
    • 25
  • d

    Damian

    06/29/2022, 11:51 PM
    Hey there, I have two pact tests - one is a simple GET request for all games and the other is a GET request to retrieve a game by ID(query param). For some reason, the pact test with the query param is throwing a
    No matching interaction found
    Any idea why the pact test for the GET request w/ a query param would be failing when it's seemingly identical to the other working pact test?
    y
    m
    t
    • 4
    • 14
  • g

    Greg Tyler

    06/30/2022, 2:22 PM
    Hello, I have a few questions about the removal of support for karma in pact-web: • As a Karma + pact user, am I right in thinking that my two options are (1) use a different test runner (and rewrite tests) or (2) pin pact-web to 9.17.x? • Will patch releases of 9.17.x always support pact-web? • Will 9.17.x receive any continuing support, e.g. security patches?
    t
    m
    • 3
    • 7
  • a

    Abhishek

    06/30/2022, 6:24 PM
    Hello Team, I am having an issue, Mock server is not starting, following error appears:-[2022-06-30 181011.622 +0000] DEBUG (19956 on): pact-node@10.17.4: Created 'C:\Users\**\node_modules\@pact-foundation\pact-node\standalone\win32-1.89.01-rc1\pact\bin\pact-mock-service.bat' process with PID: 16468 ERROR: The process "16468" not found. [2022-06-30 181012.226 +0000] DEBUG (19956 on ): pact-node@10.17.4: C:/Users/**/node_modules/@pact-foundation/pact-node/standalone/win32-1.89.01-rc1/pact/lib/ruby/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb55in `require': cannot load such file -- bundler/vendor/molinillo/lib/molinillo/delegates/specification_provider (LoadError)
    m
    • 2
    • 2
  • h

    Harris Lee

    06/30/2022, 11:36 PM
    Hello question about
    api gateway / service mesh
    When services to services interact through api gateway or service mesh, what is the boundary of the consumer test? I think from
    consumer <-> api gateway/mesh MOCK
    and generate pact then
    pact <-> api gateway/mesh + Provider
    is that right approach? but for me, api gateway / mesh is just one layer to invoke function or other services. how to write contract for that? for example, most of AWS lambda integrate with API gateway. I can see example of lambda to invoke the function to write contract test, but I am not really sure how to deal with api gateway / service mesh layer boundary. hope it makes a sense lol
    m
    • 2
    • 22
  • h

    Harris Lee

    07/04/2022, 5:48 AM
    Hello, me again lol upgrading pact to use V3, from
    9.17.2
    to
    10.0.0-beta.60
    it causes GLIBC error
    Copy code
    /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.25' not found (required by /app/node_modules/@pact-foundation/pact-core/build/Release/libpact_ffi.so)
    is there any fix / recommendation to work around that?
    m
    t
    • 3
    • 53
  • z

    Zhao Yi

    07/04/2022, 5:53 AM
    Hello, I am using
    jest
    for contract testing library. Does anyone know how I can run a single contract test in provider side? It seems every time it runs all contract tests downloaded from the broker. Is there a way to run just one?
    m
    t
    • 3
    • 7
  • a

    Artur Neumann

    07/04/2022, 10:56 AM
    Should it be possible to use matchers in content-types of a request? (V3 .59 & .60) I get
    PactffiWithBody(arg 2) expected a string
    m
    t
    • 3
    • 35
  • j

    John Williams

    07/04/2022, 11:37 PM
    Just a quick question about this Beta js version 3. The provider is written in PHP and from what I can see the issue is that because the org uses Doctrine so that many ids are autogenerated and cannot be inserted into Db with unique ids as the DB does this automatically (we cant know the id before hand). To overcome this Timothy suggested that we use the Beta version with the fromProvideState hook in the consumer test to overcome this issue. To better understand this, we still need to set up a provide state end point in the Provider ? So that the data can be inserted in the database and this will be fetched back to the consumer and injected into the consumer via this fromProviderState? Presumably the provider stuff has to be written in php?
    t
    m
    • 3
    • 49
12345...14Latest