如何用 jest 和 mock for firebase 测试本机代码

how to test react native code with jest and mock for firebase

我正在尝试使用 jest 测试 react native 方法,我的问题是修改后的值与预期值不一样。因为函数使用 firebase 我做了模拟 所以这就是我想使用的方法

 insertUserAction= async  ()=>{
 console.log("inside inserUserAction")
 var userActionKey =firebase.database().ref().child('userActions').push().key;
 firebase.database().ref('userActions/'+userActionKey).set(
  {

  userID: firebase.auth().currentUser.uid,
  ActionID:'001',
  time:new Date().getHours(),
  day:moment().format('dddd'),
  Repetition:'1',
  inRoutine:'0',
  insertedDate: new Date().getFullYear()+'/'+new Date().getMonth()+'/'+new Date().getDate(),
  })

  .then(() => {
    console.log("enter then");

    this.setState(() =>{
      return {
      userID:firebase.auth().currentUser.uid,
      ActionID:'001',
      time:new Date().getHours(),
      day:moment().format('dddd'),
      Repetition:'1'}
    });
      console.log('inserted')
  }).catch((error)=>{
      console.log(error)
  });
 }

这里是 firebase 配置

   const firebaseConfig = {


  apiKey: "******",
  authDomain: "*****",
  databaseURL: "*****",
  projectId: "*****",
  storageBucket: "*******",
  messagingSenderId: "******",
  appId: "*****",
  };

这里是测试

    import React from 'react';
    import HomeScreen from     '../screens/HomeScreen';

   import renderer from 'react-test-renderer';

  jest.mock("firebase/app", () => {
  const data = { ActionID: "unnamed" };
  const snapshot = { val: () => data };
  return {
    firebaseConfig: jest.fn().mockReturnValue({
    database: jest.fn().mockReturnValue({
      ref: jest.fn().mockReturnThis(),
      once: jest.fn(() => Promise.resolve(snapshot))
    })
  })
};
 });

test('testing Analysis feature ', () => {
 const component = renderer.create(<HomeScreen ActionID="5" />);
 const instance = component.getInstance();
 instance.insertUserAction();
 expect(instance.state.ActionID).toBe("001");
  });

我不确定模拟

正如你所看到的,没有必要模拟 firebaseConfig,因为这只需要连接到真正的数据库,但为了模拟目的,它不需要,所以基本上你只需要模拟你真正需要的东西,在这种情况下你需要这样的东西:

jest.mock("firebase/app", () => {
  const data = { ActionID: "unnamed" };
  const snapshot = { val: () => data };
  return {
    firebaseConfig: jest.fn().mockReturnValue({}),
    auth: jest.fn().mockReturnValue({ currentUser: { uid: 'uid' } }),
    database: jest.fn().mockReturnValue({
      ref: jest.fn().mockImplementation(() => ({
        child: jest.fn().mockImplementation(() => ({
          push: jest.fn().mockReturnValue({
            key: 'someValueAsKey'
          })
        })),
        set: jest.fn(),
      })),
      once: jest.fn(() => Promise.resolve(snapshot))
    })
  };
});

我保留了 firebaseConfig 模拟,因为我不想删除您的代码,如果您愿意,可以删除它。

请记住,您可以使用一些 firebase 模拟库,例如这个 https://www.npmjs.com/package/firebase-mock

希望对您有所帮助