【问题标题】:Jest mock third party object开玩笑模拟第三方对象
【发布时间】:2018-12-30 11:42:39
【问题描述】:

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

//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 正在为测试用例工作

【问题讨论】:

  • 您好,您确定 at.js 库正在加载且没有错误吗?
  • @DacreDenny window.adobe 是在其他地方定义的,所以我可以直接使用adobe 而不会出现任何错误
  • 这可能对你有用,stackoverflow.com/questions/32911630/… - 在你的情况下,不是使用这种技术来模拟 localstorage,而是使用它来模拟 adobe
  • @DacreDenny 不幸的是它不起作用。我稍后会更新建议的代码

标签: javascript unit-testing mocking jestjs


【解决方案1】:

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

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

【讨论】:

  • 不幸的是它不起作用。我已经用更多细节更新了我的代码。谢谢
猜你喜欢
  • 1970-01-01
  • 2020-08-20
  • 2021-07-03
  • 2018-10-23
  • 2019-12-21
  • 2022-12-24
  • 2019-03-23
  • 1970-01-01
相关资源
最近更新 更多