有没有办法用笑话模拟firebase模块?

问题描述 投票:0回答:1

Code.js

saveToFirebase = () => {
    let statusMsg = ""

    firebase
      .firestore()
      .collection("messages")
      .doc(this.state.field.email)
      .set(this.state.field)
      .then((statusMsg = "Your Message have been submitted successfully."))

    this.clearFields(statusMsg)
  }

Code.test.js

it("should call mock firebase module", () => {
            const docData = {
              field: {
                name: "Rob Bob",
                email: "[email protected]",
                phone: "9999999999",
                subject: "Test subject",
                message: "Test message",
              },
            }

            const docResult = {
              data: () => docData,
            }

            const get = jest.fn(() => Promise.resolve(docResult))
            const set = jest.fn()

            const doc = jest.fn(() => {
              return {
                set,
                get,
              }
            })
            const colllection = jest.fn((messages) => {
              return { doc }
            })
            const firestore = () => {
              return colllection
            }

            firebase.firestore = firestore

            const mockData = { fake: "data" }
            jest.clearAllMocks()
            wrapper.instance().saveToFirebase()
          })

在运行Code.test.js时,它抛出一个错误,即firebase.firestore().collection()不是一个函数。请建议对上面的代码进行适当的模拟firebase模块,并增加一个检查firebase是否成功返回的情况,然后调用clearFields()。

firebase testing mocking jestjs enzyme
1个回答
1
投票

你可以使用 jest.spyOn(object, methodName) 嘲讽 firebase.firestore() 功能。

例如index.jsx:

import React, { Component } from 'react';
import firebase from 'firebase';

export default class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      field: { email: '[email protected]' },
    };
  }
  clearFields(statusMsg) {
    console.log(statusMsg);
  }
  saveToFirebase = () => {
    let statusMsg = '';

    return firebase
      .firestore()
      .collection('messages')
      .doc(this.state.field.email)
      .set(this.state.field)
      .then(() => {
        statusMsg = 'Your Message have been submitted successfully.';
        this.clearFields(statusMsg);
      });
  };
  render() {
    return <div>my component</div>;
  }
}

index.test.jsx:

import MyComponent from '.';
import { shallow } from 'enzyme';
import React from 'react';
import firebase from 'firebase';

describe('61358076', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  it('should pass', async () => {
    const firestoreMock = {
      collection: jest.fn().mockReturnThis(),
      doc: jest.fn().mockReturnThis(),
      set: jest.fn().mockResolvedValueOnce(),
    };
    const clearFieldsSpy = jest.spyOn(MyComponent.prototype, 'clearFields');
    jest.spyOn(firebase, 'firestore').mockImplementationOnce(() => firestoreMock);
    const wrapper = shallow(<MyComponent></MyComponent>);
    await wrapper.instance().saveToFirebase();
    expect(firestoreMock.collection).toBeCalledWith('messages');
    expect(firestoreMock.doc).toBeCalledWith('[email protected]');
    expect(firestoreMock.set).toBeCalledWith({ email: '[email protected]' });
    expect(clearFieldsSpy).toBeCalledWith('Your Message have been submitted successfully.');
  });
});

单元测试结果,覆盖率为100%。

 PASS  stackoverflow/61358076/index.test.jsx (17.824s)
  61358076
    ✓ should pass (39ms)

  console.log stackoverflow/61358076/index.jsx:1611
    Your Message have been submitted successfully.

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |                   
 index.jsx |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        19.945s

源代码。https:/github.commrdulinreact-apollo-graphql-starter-kittreemasterstackoverflow61358076。

© www.soinside.com 2019 - 2024. All rights reserved.