[Testing] Jest Mock Function

고석진
Jan 29, 2021

--

목…

jest.fn()

jest 의 fn 함수를 이용하면 가짜 함수를 만들 수 있다.

const mockFunction = jest.fn()

mockReturnValue

jest.fn() 으로 만들어진 함수는 undefined 를 리턴한다.
특정 값을 리턴해야하는 함수가 필요하다면 mockReturnValue 를 이용하여 리턴값을 지정해 줄 수 있다.

const mockFunction = jest.fn().mockReturnValue("리턴 값 지정")
mockFunction() // 리턴 값 지정

mockResolvedValue

비동기 함수가 필요하다면 mockResolvedValue 를 이용하여 만들 수 있다.

const fetchList = jest.fn().mockResolvedValue("비동기 함수")fetchList.then(() => {}) const response = await fetchList()

mockImplementation

함수 자체의 재구현이 필요한 경우 mockImplementation 을 이용하여 구현이 가능하다.

const newFunction = jest.fn().mockImplementation(() => "새로운 함수")

이렇게 만들어진 Mock Function 들은 jest 가 지원해주는 toBeCalled Matcher 와 함께 이용이 가능하다.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

고석진
고석진

Written by 고석진

자바스크립트를 사랑하는 프론트 개발자 입니다 :)

No responses yet

Write a response