开玩笑的模拟第三方对象

时间:2018-07-23 04:50:47

标签: javascript unit-testing mocking jestjs

我需要一些有关测试第三方对象的帮助。下面是我的代码

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


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

在我的测试文件中

//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'}
    });
})

但是当我开始运行它时,app.js总是报告 ReferenceError: adobe is not defined 但是如果我将app.js更改为

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

然后测试通过,上面的adobe.target.getOffer未测试 所以我的问题是,如何测试adobe.target.getOffer部分?以及为什么测试会通过?似乎window.adobe = adobe正在测试用例中

1 个答案:

答案 0 :(得分:1)

为了将(模拟的)方法添加到全局范围,您可以在运行测试之前将它们附加到Node's global object上。喜欢:

beforeAll(() => {
  const adobe = {
    target: {
       getOffer: jest.fn()
    }
  }
  global.adobe = adobe;
})
相关问题