Last active
February 27, 2022 10:15
-
-
Save from-unknown/f02a8c79b9e1696fcf467693d86ee9db to your computer and use it in GitHub Desktop.
jest test - when need to declare variable inside mock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// fail | |
test("test1", () => { | |
const mockTest = jest.fn(() => ({ | |
testMethod: jest.fn(() => "test"), | |
})); | |
// false | |
console.log(mockTest().testMethod === mockTest().testMethod); | |
expect(mockTest().testMethod()).toBe("test"); | |
// fail - 毎回新しくjest.fn()が作られるため、呼び出された事が記録されない | |
expect(mockTest().testMethod).toBeCalled(); | |
}); | |
// success | |
test("test2", () => { | |
const testMethod = jest.fn(() => "test"); | |
const mockTest = jest.fn(() => ({ testMethod: testMethod })); | |
// true | |
console.log(mockTest().testMethod === mockTest().testMethod); | |
expect(mockTest().testMethod()).toBe("test"); | |
// success - 呼び出された事が記録されているので成功する | |
expect(mockTest().testMethod).toBeCalled(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment