简体   繁体   中英

How to unit test a function that depends on Firebase reference?

I want to unit test a function in my application that calls and updates a Firebase reference. The problem I am facing is that when I try to run the test and import the file that contains the function, I get the following error SyntaxError: Unexpected token u in JSON at position 0 which points to the line in my function file that imports my reference to Firebase.

I am using Webpack and Babel on this project, so I tried setting a resolve.alias in the webpack.config file which worked when the application was running, but did not work when I ran npm test . At this point I'm at a loss as to how I can mock out the Firebase reference so I can test the other functions of the function. Here's some sample code:

constants/index.js

import firebase from 'firebase';
const firebaseConfig = JSON.parse(unescape(`${config.FIREBASE_CONFIG}`));

const mainApp = firebase.initializeApp(firebaseConfig);

export const ref = mainApp.database().ref();

actions/settings.js

import * as actions from './';
import { ref } from '../constants';

export const updateSetting = (e, value) =>
  (dispatch) => {
     ref.child('setting')
      .set(value)
      .then(() => {
        dispatch(actions.confirmFBSave());
      })
      .catch((err) => {
        dispatch(actions.failFBSave({ text: err.code }));
      });
  };

What testing framework are you using Qunit, jasmine, mocha? With AngularFire and Angular it is much easier because you can pass a mock class in at DI, but I have also tested non angular js for server side. Then I used Sinon to get mock initializeApp and return a Mock firebase app.

You could also try https://github.com/thlorenz/proxyquire I didn't need to go that far, but I have seen it suggested. That way you are essentially intercepting the import and swap it out for something you can test with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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