简体   繁体   English

如何用玩笑和模拟测试 firebase 的反应本机代码

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

I am trying to test react native method using jest, my problem is the revised value is not the same as expected value.我正在尝试使用 jest 测试反应原生方法,我的问题是修改后的值与预期值不同。 because the function use firebase i made mock so this is the method i want to use因为 function 使用 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)
  });
 }

and here the firebase configuration这里是 firebase 配置

   const firebaseConfig = {


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

and here the test这里是测试

    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");
  });

I am not sure with the mock我不确定模拟

As you can see, it's not necessary to mock the firebaseConfig, because this is only needed to connect to real db, but for mock purpose it not needed, so basically you only need to mock what you really need, in this case you need something like this:正如你所看到的,没有必要模拟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))
    })
  };
});

I kept the firebaseConfig mock, because I didn't want to remove your code, if you want you can remove it.我保留了firebaseConfig模拟,因为我不想删除您的代码,如果您愿意,可以将其删除。

remember that you can use some firebase mock libraries, like this one https://www.npmjs.com/package/firebase-mock请记住,您可以使用一些 firebase 模拟库,例如这个https://www.npmjs.com/package/firebase-mock

I hope this can help you.我希望这可以帮助你。

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

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