'Can I mock one function exported from a typescript module that uses ES6 import style

I have been struggling with some specific ES6 importing-style and using with Jest mocking in typescript.

It's very specific, so I wrote this example puzzle to best ask for help.

// animals.ts

export function getCanine() {
    return 'dog';
}

export function getFeline() {
    return 'cat';
}

// animals.test.ts

import { getCanine, getFeline } from './animals'; // you are not allowed to change this line
// Not changing the above line is _fundamental_ to my question.
// Lines may be added above or below it.

describe('Jest mocking tests', function () {

    it('output of getCanine() is successfully changed', async () => {

        expect(getCanine()).toEqual('dog');
        expect(getFeline()).toEqual('cat');

        // how do I mock getCanine() to return 'wolf' instead?

        expect(getCanine()).toEqual('wolf');
        expect(getFeline()).toEqual('cat');
    });
});


Solution 1:[1]

I think this would be a way to achieve that:

/* ... */
expect(getCanine()).toEqual('dog');
expect(getFeline()).toEqual('cat');

getCanine = jest.fn(getCanine).mockReturnValueOnce('wolf');

expect(getCanine()).toEqual('wolf');

mockFn.mockReturnValueOnce has been used so that the next time you're invoking getCanine(), it will fall back to the default implementation(i.e. returning 'dog').

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrei Gătej