首页 > 解决方案 > 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 日历。我究竟做错了什么?

标签: javascriptunit-testinggoogle-calendar-apisinonstubbing

解决方案


您可以使用 .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


推荐阅读