Jest Mock/Spy using typescript

52 Views Asked by At

I'm trying to mock/spy a function - not really sure, already got confused on the differences.

The problem is that this function is anonymous function + it is not exported + other function (which i what to test) called it.

for example assume i have this functions and i what to test 'create':

async function create(id: string, name: string){
    const [suf, pre] = await Promise.all([generateSuf(id), generatePre(id)]);
    return suf + name + pre;
}

async function generateSuf(id){
    return id + 1;
}

async function generatePre(id){
    return id - 1;
}

export { create };

i want to Mock/Spy the functions generateSuf(), and generatePre() to make them always return the value '1' for example.

Already tried to mock the whole file like:

jest.mock('../../src/services/flow', () => {
    const original = jest.requireActual('../../src/services/flow');
    return {
        ...original,
        generateSuf : jest.fn().mockReturnValue('1')
    };
});

With several orders. Try to make: jest.spyOn('../../src/services/flow', 'generateSuf'); Nothing worked.

i want my test to be something like this:

it('should create a user', async () => {
    result = await create('3', '4');
    expect(result).toBe('141');
})
0

There are 0 best solutions below