简体   繁体   English

google-calendar sinon 存根似乎不起作用

[英]google-calendar sinon stub doesn't seem to work

In my calendar.spec.js , I have:在我的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()
})

In my calendar.js , I have:在我的calendar.js中,我有:

const { google } = require('googleapis')
const googleCalendar = google.calendar('v3')
let { data } = await googleCalendar.calendarList.list({
  auth: oauth2Client
})

But it doesn't appear to be stubbed.但它似乎没有被存根。 It goes ahead and tries to connect to Google Calendar.它继续并尝试连接到 Google 日历。 What am I doing wrong?我究竟做错了什么?

You can mock the entire googleapis module with mock-require .您可以使用mock-require模拟整个googleapis模块。

const mock = require('mock-require');

mock('googleapis', {
  google: {
    calendar: () => ({
      calendarList: {
        list: () => {
          return Promise.resolve({
            data: {
              foo: 'bar'
            }
          });
        }
      }
    })
  }
});

Once you mocked it, your module will consume the mocked module instead of the original so you can test it.一旦你模拟了它,你的模块将使用模拟的模块而不是原来的模块,这样你就可以测试它了。 So if you module is exposing a method that calls the API, something like that:因此,如果您的模块公开了一个调用 API 的方法,则类似于:

exports.init = async () => {
  const { google } = require('googleapis');
  const googleCalendar = google.calendar('v3');
  let { data } = await googleCalendar.calendarList.list({
    auth: 'auth'
  });

  return data;
}

The test will be测试将是

describe('test', () => {
  it('should call the api and console the output', async () => {
    const result = await init();
    assert.isTrue(result.foo === 'bar');
  });
});

Here is a small repo to play with it: https://github.com/moshfeu/mock-google-apis这是一个可以使用它的小仓库:https://github.com/moshfeu/mock-google-apis

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM