Adyen / adyen-node-api-library

Adyen API Library for Node.js

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Best practices for mocking with jest

momentiris opened this issue · comments

Hello!

I'm currently bumping from v13 to 14.4.0 and have run into some problems with our current test suite.
We've been pleasantly mocking so far and it has looked something like this:

it('works', () => {
  jest.spyOn(CheckoutAPI.prototype, 'payments').mockResolvedValueOnce('foo')

 const result = await request('http://our-route-that-uses-checkout-payments').send()

 expect(result.data).toBe('foo')
})

This has been working great. However, as we're migrating to 14.4.0, I notice that the above mocking does work anymore.
It's a bit confusing but I think it's something with how you've restructured your modules. Now, PaymentsApi is a nested class of CheckoutAPI, and they both require constructor arguments, so I can't no longer mock them because i get some error like
config is not defined. I suspect this is because of the missing constructor arguments when trying to mock.

So now the current workaround I have is to first mock your entire library, and then use jest.spyOn(...) not on your modules, but rather spy on the instantiated client that our app uses:

jest.mock('@adyen/api-library', () => ({
  ...jest.requireActual('@adyen/api-library'),
  CheckoutAPI: function () {
    this.PaymentsApi = {
      paymentMethods: jest.fn(),
      payments: jest.fn(),
      paymentsDetails: jest.fn(),
    }
    this.ModificationsApi = {
      cancelAuthorisedPayment: jest.fn(),
      cancelAuthorisedPaymentByPspReference: jest.fn(),
    }
  },
}))

...

jest
  .spyOn(payment_adapter.checkout.PaymentsApi, 'paymentMethods')
  .mockResolvedValueOnce(...)

Although this works, it's just a hassle.

Do you have any suggested approach on how to deal with jest mocking when using your library?

Thanks!

Hi @momentiris,

Thanks for reaching out here. I'm not too familiar with jest, however if you'd want some inspiration you can always check out our own test suite (using nock though). We mock the httpclient to see how our library handles the raw api requests/responses. Hope that helps :)

Best, Jilling
Adyen