有没有办法以开玩笑的方式模拟 firebase 模块?

Rau*_*wal 2 testing mocking firebase jestjs enzyme

代码.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)
  }
Run Code Online (Sandbox Code Playgroud)

代码.test.js

it("should call mock firebase module", () => {
            const docData = {
              field: {
                name: "Rob Bob",
                email: "rob@bob.com",
                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()
          })
Run Code Online (Sandbox Code Playgroud)

运行 Code.test.js 时,它会抛出一个错误,指出 firebase.firestore().collection() 不是函数。请建议对上述代码的 firebase 模块进行适当的模拟,并添加一个案例来检查 firebase 是否已成功返回,然后调用clearFields()。

sli*_*wp2 5

您可以使用jest.spyOn(object, methodName)来模拟firebase.firestore()函数。

\n

例如\n index.jsx:

\n
import React, { Component } from \'react\';\nimport firebase from \'firebase\';\n\nexport default class MyComponent extends Component {\n  constructor(props) {\n    super(props);\n    this.state = {\n      field: { email: \'mock@example.com\' },\n    };\n  }\n  clearFields(statusMsg) {\n    console.log(statusMsg);\n  }\n  saveToFirebase = () => {\n    let statusMsg = \'\';\n\n    return firebase\n      .firestore()\n      .collection(\'messages\')\n      .doc(this.state.field.email)\n      .set(this.state.field)\n      .then(() => {\n        statusMsg = \'Your Message have been submitted successfully.\';\n        this.clearFields(statusMsg);\n      });\n  };\n  render() {\n    return <div>my component</div>;\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

index.test.jsx:

\n
import MyComponent from \'.\';\nimport { shallow } from \'enzyme\';\nimport React from \'react\';\nimport firebase from \'firebase\';\n\ndescribe(\'61358076\', () => {\n  afterEach(() => {\n    jest.restoreAllMocks();\n  });\n  it(\'should pass\', async () => {\n    const firestoreMock = {\n      collection: jest.fn().mockReturnThis(),\n      doc: jest.fn().mockReturnThis(),\n      set: jest.fn().mockResolvedValueOnce(),\n    };\n    const clearFieldsSpy = jest.spyOn(MyComponent.prototype, \'clearFields\');\n    jest.spyOn(firebase, \'firestore\').mockImplementationOnce(() => firestoreMock);\n    const wrapper = shallow(<MyComponent></MyComponent>);\n    await wrapper.instance().saveToFirebase();\n    expect(firestoreMock.collection).toBeCalledWith(\'messages\');\n    expect(firestoreMock.doc).toBeCalledWith(\'mock@example.com\');\n    expect(firestoreMock.set).toBeCalledWith({ email: \'mock@example.com\' });\n    expect(clearFieldsSpy).toBeCalledWith(\'Your Message have been submitted successfully.\');\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n

100%覆盖率的单元测试结果:

\n
 PASS  stackoverflow/61358076/index.test.jsx (17.824s)\n  61358076\n    \xe2\x9c\x93 should pass (39ms)\n\n  console.log stackoverflow/61358076/index.jsx:1611\n    Your Message have been submitted successfully.\n\n-----------|---------|----------|---------|---------|-------------------\nFile       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s \n-----------|---------|----------|---------|---------|-------------------\nAll files  |     100 |      100 |     100 |     100 |                   \n index.jsx |     100 |      100 |     100 |     100 |                   \n-----------|---------|----------|---------|---------|-------------------\nTest Suites: 1 passed, 1 total\nTests:       1 passed, 1 total\nSnapshots:   0 total\nTime:        19.945s\n
Run Code Online (Sandbox Code Playgroud)\n

源代码:https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61358076

\n

  • 有趣的测试电子邮件 (2认同)