在我的calendar.spec.js中,我有:
const { google } = require('googleapis')
const googleCalendar = google.calendar('v3')
...
before(() => {
sinon.stub(googleCalendar.calendarList, 'list').resolves({ data: true })
})
after(() => {
googleCalendar.calendarList.list.restore()
})在我的calendar.js中,我有:
const { google } = require('googleapis')
const googleCalendar = google.calendar('v3')
let { data } = await googleCalendar.calendarList.list({
auth: oauth2Client
})但它看起来并没有被卡住。它继续尝试连接到Google Calendar。我做错了什么?
发布于 2019-10-07 22:30:51
您可以用mock-require模拟整个googleapis模块。
const mock = require('mock-require');
mock('googleapis', {
google: {
calendar: () => ({
calendarList: {
list: () => {
return Promise.resolve({
data: {
foo: 'bar'
}
});
}
}
})
}
});一旦你模拟了它,你的模块将使用模拟的模块而不是原来的模块,这样你就可以测试它了。因此,如果您的模块公开了一个调用API的方法,则如下所示:
exports.init = async () => {
const { google } = require('googleapis');
const googleCalendar = google.calendar('v3');
let { data } = await googleCalendar.calendarList.list({
auth: 'auth'
});
return data;
}测试将是
describe('test', () => {
it('should call the api and console the output', async () => {
const result = await init();
assert.isTrue(result.foo === 'bar');
});
});下面是一个可以使用它的小repo:https://github.com/moshfeu/mock-google-apis
https://stackoverflow.com/questions/58220773
复制相似问题