开玩笑的模拟无法解决每个注入的值 [英] Jest mock not resolving to each injected value

查看:95
本文介绍了开玩笑的模拟无法解决每个注入的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的functions/send.js模块中测试名为myCloudFn的Firebase云功能.我的测试在functions/test/send.spec.js:

I'm trying to test a Firebase cloud function named myCloudFn in my functions/send.js module. My tests are in functions/test/send.spec.js:

// send.js
const admin = require('firebase-admin');

async function myCloudFn (email) {
  const authUser = await admin.auth().getUserByEmail(email);
  return authUser;
}

module.exports = { myCloudFn };

// send.spec.js
const send = require('../send.js');

jest.mock('firebase-admin', () => ({
  auth: () => ({
    getUserByEmail: jest.fn()
      .mockResolvedValueOnce({ uid: 'foo-bar' })
      .mockResolvedValueOnce(null),
  }),
}));

describe('send.js', () => {
  it('returns authUser from myCloudFn()', async () => {
    const email = 'foo@bar.com';
    const responseOptions = [{ uid: 'foo-bar' }, null];
    const responsePromises = responseOptions.map(() => send.myCloudFn(email));
    const responses = await Promise.all(responsePromises);
    expect(responses[0]).toStrictEqual(responseOptions[0]);
    expect(responses[1]).toStrictEqual(responseOptions[1]);
  });
});

测试在第一个断言上通过,但在第二个断言上失败.测试两次都返回相同的{ uid: 'foo-bar' }对象,但是我希望测试响应值第二次是null.我想念什么?

The test passes on the first assertion, but fails on the second. The test returns the same { uid: 'foo-bar' } object both times, but I want the test response value to be null the second time. What am I missing?

推荐答案

每个auth调用都会创建一个新的getUserByEmail间谍,但不会被多次调用.

A new getUserByEmail spy is created on each auth call, it isn't called more than once.

它应该是:

const mockGetUserByEmail = jest.fn();
jest.mock('firebase-admin', () => ({
  auth: () => ({
    getUserByEmail: mockGetUserByEmail
  })
}));

...
mockGetUserByEmail
  .mockResolvedValueOnce({ uid: 'foo-bar' })
  .mockResolvedValueOnce(null);
const responsePromises = responseOptions.map(() => send.myCloudFn(email));
...

这篇关于开玩笑的模拟无法解决每个注入的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆