How to mock up a single imported function using Jest

Let's assume that you want to mock up non-default exported functions:

functions.js

javascript
const sum = () => console.log('Sum')
const sub = () => console.log('Sub')

export { sum, sub }

main.js

javascript
import { sum, sub } from './functions'

sum()
sub()

// Sum
// Sub

test.js

javascript
import { sum, sub } from './functions'
jest.mock('./functions')

it('mocking up the functions' => {

    sum.mockImplementation(_ => true)
    sub.mockImplementation(_ => false)

    expect(sum()).toBe(true)
    expect(sub()).toBe(false)

})

And here is the result:

terminal
 PASS  src/Tests/test.test.js
  ✓ mocking up the functions (2 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.472 s, estimated 2 s

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.