我需要一些关于测试第三方对象的帮助。下面是我的代码
//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
正在为测试用例工作
发布于 2018-07-23 15:26:11
为了将(模拟的)方法添加到全局作用域,您可以在测试运行之前将它们附加到Node's global
object上。像这样:
beforeAll(() => {
const adobe = {
target: {
getOffer: jest.fn()
}
}
global.adobe = adobe;
})
https://stackoverflow.com/questions/51471716
复制相似问题