4

I need some help on testing a third party object. Below is my code

//app.js
export const specialFunction = (offer) => {
   adobe.target.applyOffer({
       mbox: 'container',
       offer
   })
}


adobe.target.getOffer({
  mbox: 'container',
  success: (offer) => {
     specialFunction(offer);
  }
})

in my test file

//app.test.js
import { specialFunction } from './app';

beforeAll(() => {
  const adobe = {
     target: {
       getOffer: jest.fn(),
       applyOffer: jest.fn()
     }
  }
  window.adobe = adobe;
});
it('test function', () => {
    specialFunction({foo: 'bar'});
    expect(adobe.target.applyOffer).toHaveBeenCalledWith({
        mbox: 'container',
        offer: {foo: 'bar'}
    });
})

but when I started to run it,app.js always reports ReferenceError: adobe is not defined but if I change the app.js to be

typeof adobe !== 'undefined' && adobe.target.getOffer({
      mbox: 'container',
      success: (offer) => {
         specialFunction(offer);
      }
    })

then test passed, with the above adobe.target.getOffer not tested so my question is, how to test adobe.target.getOffer part? and also why the test would pass? seems window.adobe = adobe is working for the test case

peace and love
  • 239
  • 4
  • 13
  • Hi, are you sure that the `at.js` library is being loaded without errors? – Dacre Denny Jul 23 '18 at 05:05
  • @DacreDenny `window.adobe` is defined somewhere else, so I can use `adobe` directly without any error – peace and love Jul 23 '18 at 05:15
  • this might be of use to you, https://stackoverflow.com/questions/32911630/how-do-i-deal-with-localstorage-in-jest-tests#32911774 - in your case, instead of using this technique to mock `localstorage`, you would instead use it to mock `adobe` – Dacre Denny Jul 23 '18 at 05:21
  • @DacreDenny it does not work unfortunately. I will update the suggested code later – peace and love Jul 23 '18 at 06:14

1 Answers1

2

In order to add (mocked) methods to the global scope you can append them on Node's global object before your tests run. Like:

beforeAll(() => {
  const adobe = {
    target: {
       getOffer: jest.fn()
    }
  }
  global.adobe = adobe;
})
Andrea Carraro
  • 9,731
  • 5
  • 33
  • 57