google-日历 sinon 存根似乎不起作用
google-calendar sinon stub doesn't seem to work
在我的 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 日历。我做错了什么?
您可以使用 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');
});
});
这是一个可以玩的小仓库:https://github.com/moshfeu/mock-google-apis
在我的 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 日历。我做错了什么?
您可以使用 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');
});
});
这是一个可以玩的小仓库:https://github.com/moshfeu/mock-google-apis