Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mocking gatsby in __mocks__ not cleaning up after tests #26795

Closed
AbbottSoft opened this issue Sep 6, 2020 · 1 comment
Closed

Mocking gatsby in __mocks__ not cleaning up after tests #26795

AbbottSoft opened this issue Sep 6, 2020 · 1 comment
Labels
type: bug An issue or pull request relating to a bug in Gatsby

Comments

@AbbottSoft
Copy link

Description

When writing jest unit tests and mocking gatsby in the __mocks__ directory in the root of the project as instructed here, I would expect that the global object would clean up after itself after each test case as there seems to be no straight forward way to handle cleanup. However, when parts of the mocked gatsby are used in within a test, the state of the mocked gatsby object persists between describe blocks, providing incorrect outcomes.

Steps to reproduce

Setup a gatsby-starter-default project and setup jest unit testing following Steps 1-3 in the instructions presented in the official Gatsby documentation with the following modifications.

__mocks__/gatsby.js

const React = require("react")
const gatsby = jest.requireActual("gatsby")

module.exports = {
  ...gatsby,
  graphql: jest.fn(),
  navigate: jest.fn(),
  Link: jest.fn().mockImplementation(
    // these props are invalid for an `a` tag
    ({
      activeClassName,
      activeStyle,
      getProps,
      innerRef,
      partiallyActive,
      ref,
      replace,
      to,
      ...rest
    }) =>
      React.createElement("a", {
        ...rest,
        href: to,
      })
  ),
  StaticQuery: jest.fn(),
  useStaticQuery: jest.fn(),
}

Once you have finished those steps, create the following files.

src/foo.js

import { navigate } from "gatsby"

export const onLoginFinished = isSuccessful => {
  if (isSuccessful) {
    navigate("/bar")
  }
}

src/foo.test.js

import { navigate } from "gatsby"

import { onLoginFinished } from "./foo"

describe("onLoginFinished", () => {
  describe("when successful", () => {
    beforeEach(() => {
      onLoginFinished(true)
    })

    it("navigates to the success path", () => {
      expect(navigate).toHaveBeenCalledWith("/bar")
    })
  })

  describe("when unsuccessful", () => {
    beforeEach(() => {
      onLoginFinished(false)
    })

    it("does not navigate", () => {
      expect(navigate).not.toHaveBeenCalled()
    })
  })
})

Once you have created the tests, run the following command.

jest

Expected result

I would have expected both tests to pass.

Actual result

 FAIL  src/foo.test.js
  onLoginFinished
    when successful
      ✓ navigates to the success path (2 ms)
    when unsuccessful
      ✕ does not navigate (1 ms)

  ● onLoginFinished › when unsuccessful › does not navigate

    expect(jest.fn()).not.toHaveBeenCalled()

    Expected number of calls: 0
    Received number of calls: 1

    1: "/bar"

      20 |
      21 |     it("does not navigate", () => {
    > 22 |       expect(navigate).not.toHaveBeenCalled()
         |                            ^
      23 |     })
      24 |   })
      25 | })

      at Object.<anonymous> (src/foo.test.js:22:28)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        1.139 s
Ran all test suites.
npm ERR! Test failed.  See above for more details.

Environment

System:
OS: macOS 10.15.6
CPU: (16) x64 Intel(R) Core(TM) i9-9980HK CPU @ 2.40GHz
Shell: 5.7.1 - /bin/zsh
Binaries:
Node: 14.8.0 - ~/.nvm/versions/node/v14.8.0/bin/node
Yarn: 1.21.1 - /usr/local/bin/yarn
npm: 6.14.7 - ~/.nvm/versions/node/v14.8.0/bin/npm
Languages:
Python: 3.7.3 - /Users/putauserhere/.pyenv/shims/python
Browsers:
Chrome: 85.0.4183.83
Firefox: 80.0.1
Safari: 13.1.2
npmPackages:
gatsby: ^2.24.50 => 2.24.50
gatsby-image: ^2.4.16 => 2.4.16
gatsby-plugin-manifest: ^2.4.24 => 2.4.24
gatsby-plugin-offline: ^3.2.24 => 3.2.24
gatsby-plugin-react-helmet: ^3.3.10 => 3.3.10
gatsby-plugin-sharp: ^2.6.28 => 2.6.28
gatsby-source-filesystem: ^2.3.25 => 2.3.25
gatsby-transformer-sharp: ^2.5.13 => 2.5.13
npmGlobalPackages:
gatsby-cli: 2.12.87

Is there some part of this I am missing? Thanks!

@AbbottSoft AbbottSoft added the type: bug An issue or pull request relating to a bug in Gatsby label Sep 6, 2020
@gatsbot gatsbot bot added the status: triage needed Issue or pull request that need to be triaged and assigned to a reviewer label Sep 6, 2020
@AbbottSoft
Copy link
Author

Resolved this issue by adding clearMocks to jest.config.js. I have created PR #26802 to the gatsby docs to address this.

@LekoArts LekoArts removed the status: triage needed Issue or pull request that need to be triaged and assigned to a reviewer label Sep 7, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: bug An issue or pull request relating to a bug in Gatsby
Projects
None yet
Development

No branches or pull requests

2 participants