【发布时间】: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