簡體   English   中英

如何用玩笑和模擬測試 firebase 的反應本機代碼

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

我正在嘗試使用 jest 測試反應原生方法,我的問題是修改后的值與預期值不同。 因為 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)
  });
 }

這里是 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

我希望這可以幫助你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM