Jest模拟第三方对象

4

我需要帮助测试第三方对象。以下是我的代码:

//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未定义。但是如果我将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 库被正确加载了吗? - Dacre Denny
@DacreDenny window.adobe 在其他地方已经定义,所以我可以直接使用 adobe 而不会出现任何错误。 - peace and love
这可能对你有用,https://dev59.com/31wY5IYBdhLWcg3wLFOw - 在你的情况下,你将使用这种技术来模拟“localstorage”,而不是使用它来模拟“adobe”。 - Dacre Denny
@DacreDenny,不幸的是它不起作用。稍后我会更新建议的代码。 - peace and love
1个回答

2
为了在测试运行之前将(模拟)方法添加到全局范围中,您可以将它们附加到Node的global对象上。例如:
beforeAll(() => {
  const adobe = {
    target: {
       getOffer: jest.fn()
    }
  }
  global.adobe = adobe;
})

不幸的是,它不能工作。我已经更新了我的代码并加入了更多细节。谢谢。 - peace and love

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接