Skip to content

Instantly share code, notes, and snippets.

@ctgardner
Last active December 7, 2017 23:31
Show Gist options
  • Save ctgardner/db351b51fd4e495dc364f622d7e2efb4 to your computer and use it in GitHub Desktop.
Save ctgardner/db351b51fd4e495dc364f622d7e2efb4 to your computer and use it in GitHub Desktop.
Mocking ES6 instance methods with jest
// MyClass/index.js
export class MyClass {
foo() { /* do something */ }
}
// DependentClass/index.js
import { MyClass } from "../MyClass"
export class DependentClass {
bar() {
const foo = new MyClass().foo()
// do something
}
}
// DependentClass/tests/index.test.js
import { MyClass } from "../../MyClass"
jest.mock("../../MyClass")
const mockFoo = jest.fn()
MyClass.mockImplementation(() => {
return { foo: mockFoo }
})
describe("when foo returns false", () => {
beforeEach(() => {
mockFoo.mockReturnValue(false)
})
it("does something", () => {
// assertions
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment