Javascript 在vuejs中测试firebase函数

Javascript 在vuejs中测试firebase函数,javascript,firebase,unit-testing,vue.js,jestjs,Javascript,Firebase,Unit Testing,Vue.js,Jestjs,我想对我的vue组件进行单元测试。由于我与firebase合作,这有点困难 首先,我创建了一个\uuuu mocks\uuu文件夹来包含我所有的模拟函数。在该文件夹中,我创建了firebase.js: import * as firebase from 'firebase'; const onAuthStateChanged = jest.fn(); const getRedirectResult = jest.fn(() => Promise.resolve({ user: {

我想对我的vue组件进行单元测试。由于我与firebase合作,这有点困难

首先,我创建了一个
\uuuu mocks\uuu
文件夹来包含我所有的模拟函数。在该文件夹中,我创建了
firebase.js

import * as firebase from 'firebase';

const onAuthStateChanged = jest.fn();

const getRedirectResult = jest.fn(() => Promise.resolve({
  user: {
    displayName: 'redirectResultTestDisplayName',
    email: 'redirectTest@test.com',
    emailVerified: true,
  },
}));

const sendEmailVerification = jest.fn(() => Promise.resolve('result of sendEmailVerification'));

const sendPasswordResetEmail = jest.fn(() => Promise.resolve());

const createUserWithEmailAndPassword = jest.fn(() => {
  console.log('heeeeelllo');
  Promise.resolve({
    user: {
      displayName: 'redirectResultTestDisplayName',
      email: 'redirectTest@test.com',
      emailVerified: true,
    },
  });
});

const signInWithEmailAndPassword = jest.fn(() => Promise.resolve('result of signInWithEmailAndPassword'));

const signInWithRedirect = jest.fn(() => Promise.resolve('result of signInWithRedirect'));

const initializeApp = jest // eslint-disable-line no-unused-vars
  .spyOn(firebase, 'initializeApp')
  .mockImplementation(() => ({
    auth: () => ({
      createUserWithEmailAndPassword,
      signInWithEmailAndPassword,
      currentUser: {
        sendEmailVerification,
      },
      signInWithRedirect,
    }),
  }));

jest.spyOn(firebase, 'auth').mockImplementation(() => ({
  onAuthStateChanged,
  currentUser: {
    displayName: 'testDisplayName',
    email: 'test@test.com',
    emailVerified: true,
  },
  getRedirectResult,
  sendPasswordResetEmail,
}));

firebase.auth.FacebookAuthProvider = jest.fn(() => {});
firebase.auth.GoogleAuthProvider = jest.fn(() => {});
import { mount } from '@vue/test-utils';
import Vue from 'vue';
import EmailSignupLogin from '@/components/email-signup-login';

jest.mock('../../__mocks__/firebase');

describe('EmailSignupLogin', () => {
  let wrapper;
  const mockFunction = jest.fn();

  beforeEach(() => {
    wrapper = mount(EmailSignupLogin, {
      data() {
        return {
          password: '123456',
          passwordReenter: '123456',
          emailAdress: 'test@test.com',
        };
      },
      store: {
        actions: {
          setUser: mockFunction,
        },
      },
    });
  });

  describe('methods', () => {
    describe('#registerViaEmail', () => {
      it('calls mockFunction', async () => {
        await wrapper.vm.registerViaEmail();

        expect(mockFunction).toHaveBeenCalled();
      });
    });
  });
});
这个文件,我是从:

我要测试的组件名为
EmailSignupLogin
。在这种情况下,我想测试
registerviemail
-方法:

methods: {
    registerViaEmail() {
      if (this.password.length > 0 && this.password === this.passwordReenter) {
        firebase.auth().createUserWithEmailAndPassword(this.emailAdress, this.password).then((result) => {
          const { user } = result;
          console.log(result);
          this.setUser(user);
          this.$router.push('/stocks');
        }).catch((error) => {
          const errorCode = error.code;
          const errorMessage = error.message;
          this.error = errorMessage;
          console.error(errorCode, errorMessage);
        });
      } else {
        this.error = 'passwords not matching';
      }
    },
  },
现在转到我的测试文件(
email signup login.spec.js
):

registerviemail
-方法中,我调用
setUser
-操作,这是一个vuex操作


问题是它似乎没有从
\uuuumocks\uuuu/firebase.js
调用我的模拟函数。有人能告诉我为什么吗?

您的代码中出现了几个问题:

  • registerviemail()
    不是
    async
    (不返回
    Promise
    ),因此
    wait
    调用过早返回,此时您的测试尝试断言尚未发生的内容。要解决此问题,只需使用
    承诺
    包装函数体:
  • registerviemail(){
    返回新承诺((解决、拒绝)=>{
    if(this.password.length>0&&this.password===this.password重新输入){
    firebase.auth().createUserWithEmailAndPassword(this.EmailAddress,this.password)。然后((结果)=>{
    //...
    解决()
    }).catch((错误)=>{
    //...
    拒绝
    });
    }否则{
    //...
    拒绝
    }
    })
    },
    
  • 您提到的不适用于Jest
    \uuuu mocks\uuuu
    。脚本本身直接修改
    firebase
    对象,用mock替换其方法/属性。要使用脚本,只需在导入使用
    firebase
    的测试模块之前导入脚本:
  • import./firebase mock'//{
    console.log('heeeello')
    
    return/*您面临的错误是什么?如果不是,您能否尝试将所需的函数添加到测试文件中一次,然后检查wokring是否正常?