javascript - google-calendar sinon 存根似乎不起作用
问题描述
在我的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 模拟整个googleapis
模块mock-require
。
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
推荐阅读
- kubernetes-helm - Helm:将计算值作为值注入依赖关系图中
- ios - 如何迭代一些符合 View 协议的协议数组?
- c++ - 如果条件为真,则将表达式添加到循环中
- ajax - 如何使用 XMLHttpRequest 提交 Pardot 表单处理程序?
- r - 如何解决 install_github 失败并出现错误系统命令“Rcmd.exe”失败,退出状态:1,stdout + stderr?
- c# - 如何检测在 c# webview2 中打开的新窗口
- python - 使用 BeautifulSoup python 从 div 中的 p 标签获取文本
- python-3.x - 需要帮助解释来自 Google API 的一些数据点
- r - 当 B 列和 C 列中有 2 个条件时,A 列中的最大值
- java - 如何检索存储在 LinkedList 中的对象的字段值?