【问题标题】:Jest.fn().mockReturnValue returns undefinedJest.fn().mockReturnValue 返回 undefined
【发布时间】:2021-12-20 07:43:35
【问题描述】:

下面提到的模拟函数在名为 useFirestore 的文件中使用时会出现以下错误:Cannot read property 'collection' of undefined

firebase.js

import Firebase from 'firebase/app';
import 'firebase/storage';
import 'firebase/firestore';
import 'firebase/auth';

const config = {'// Firebase config'};

const firebase = !Firebase.apps.length ? Firebase.initializeApp(config) : Firebase.app;

export const { serverTimestamp } = Firebase.firestore.FieldValue;

export default firebase;

setupTests.js

import '@testing-library/jest-dom';


jest.mock('./firebase', () => ({
  storage: jest.fn(),
  firestore: jest.fn().mockReturnedValue({
    collection: jest.fn().mockReturnThis(),
    orderBy: jest.fn().mockReturnThis(),
    onSnapshot: jest.fn().mockReturnThis(),
  }),
}));

自定义挂钩

import firebase from '../firebase';

function useFirestore(collectionName) {
  const [docs, setDocs] = React.useState(null);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    const unsub = firebase
      .firestore() // logs cannot read property collection of undefined
      .collection(collectionName)
      .orderBy('createdAt', 'desc')
      .onSnapshot(
        (snapshot) => {
          setDocs(snapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() })));
          setLoading(false);
        },
        (err) => {
          console.log(err);
        }
      );
    return unsub;
  }, [collectionName]);

  return {
    docs,
    loading,
  };
}

export default useFirestore;

jest.config.js

module.exports = {
  collectCoverageFrom: [
    'src/**/*.{js,jsx}',
    '!<rootDir>/node_modules/',
    '!<rootDir>/coverage/',
    '!<rootDir>/build/',
  ],
  moduleNameMapper: { '\\.(css|scss)$': '<rootDir>/src/utils/__mocks__/stylemock.js' },
  setupFilesAfterEnv: ['<rootDir>/src/setupTests.js'],
};

如上所述,上面的配置返回未定义。但是,当我将 firestore 的模拟实现更改为以下内容时,它可以正常工作。

jest.mock('./firebase', () => ({
  storage: jest.fn(),
  firestore: () => ({ // not using jest.fn() and mockReturnValue
    collection: jest.fn().mockReturnThis(),
    orderBy: jest.fn().mockReturnThis(),
    onSnapshot: jest.fn().mockReturnThis(),
  }),
}));

如果这里有什么问题,请指导。谢谢

【问题讨论】:

    标签: jestjs mocking babel-jest


    【解决方案1】:

    只是一个错字,我的朋友!在jest.Mock 类型上没有mockReturnedValue 这样的东西,您可能想使用mockReturnValue

    【讨论】:

      猜你喜欢
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-13
      • 2022-01-22
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多