0
votes

I have created a mock file for mangopay2-nodejs-sdk in order to simulate payment failure for my Jest tests:

// __mocks__/mangopay2-nodejs-sdk.ts
import BaseMangoPay from 'mangopay2-nodejs-sdk';

export default class MangoPay extends BaseMangoPay {
  static __willFail: boolean = false;

  constructor(config: BaseMangoPay.Config) {
    super(config);

    // Mocked stuff.

    this.CardPreAuthorizations = {
      create: (
        data: cardPreAuthorization.CreateCardPreAuthorization,
      ): Promise<cardPreAuthorization.CardPreAuthorizationData> => Promise.resolve({
        ...data,
        Id: '1337',
        Status: MangoPay.__willFail ? 'FAILED' : 'SUCCEEDED',
      }),
    };
  }
}

Note: The original import is a class that has to be instantiated with a configuration to work properly.

I added an extra __willFail static property to make my mock failing when I want on my tests:

import MangoPay from 'mangopay2-nodejs-sdk';

describe('payment failures', () => {
  beforeEach(() => {
    MangoPay.__willFail = true;
  });
  afterAll(() => {
    MangoPay.__willFail = false;
  });

  // The tests.
});

This is working perfectly fine. However, typescript does not recognize the __willFail extra static property of my mocked class:

Property '__willFail' does not exist on type 'typeof MangoPay'.ts(2339)

I expected this error of course, but I don't know how to solve it.

I found similar answers like this one: https://stackoverflow.com/a/53222290/1731473

But this is working with imported variable.

How can I apply this kind of method to make Typescript working with my extra static property?

1
The answer you linked shows the exact way how it's done. You need to import MockMangoPay from __mocks__ just to do (MangoPay as typeof MockMangoPay).__willFail.Estus Flask
The difference is the example show a ready to use imported object. Here, I have to instantiate the MangoPay instance on the source code (not on test thanks to static property).Soullivaneuh
I am currently stuck about how to manage with imports and I don't need to instanciate the instance on tests. I just need TS to check the right typing. May you give a complete example on the answer? :-)Soullivaneuh

1 Answers

0
votes

The approach described in this answer is applicable to this case. There needs to be a separate type import for type assertions:

import MangoPay from 'mangopay2-nodejs-sdk';
import MockMangoPay from '.../__mocks__/mangopay2-nodejs-sdk'; 
...    
(MangoPay as typeof MockMangoPay).__willFail = true;

Without that, type safety needs to be disabled, which can be acceptable for one-off use in tests:

(MangoPay as any).__willFail = true;