Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest jest.fn it's being called but the expect fails

I am new to testing with jest, and I wrote the below test. I mocked with jest a function and passed it as a parameter. however when run the test, in the logs I can see the function onSuccess was called. but the expect fails with the error below the code.

how am I supposed to assert the onSuccess = jest.fn() was called?

Test

 it('should create product correctly', async () => {
            const store = mockStore()
            const onSuccess = jest.fn(() => console.log("I was called"))
            const onError = jest.fn()
            const CreateProductApiMock = CreateProductApi as jest.Mock
            const productRequest = {id: 1} as Product

            CreateProductApiMock.mockResolvedValue(Promise.resolve({
                data: "any"
            } as AxiosResponse<string>))


            await store.dispatch(createProduct(productRequest, onSuccess, onError, "jwt"))
            expect(CreateProductApiMock).toHaveBeenCalledWith({"id": 1}, "jwt")
            expect(onSuccess).toHaveBeenCalledTimes(1)
        })

Logs:

console.log src/__tests__/components/product/product-slice.test.ts:133
    I've was called


Error: expect(jest.fn()).toHaveBeenCalledTimes(expected)

Expected number of calls: 1
Received number of calls: 0
like image 267
Rubenex Avatar asked Nov 19 '25 18:11

Rubenex


1 Answers

Add await onSuccess right before expect(onSuccess).toHaveBeenCalledTimes(1)

Like so:

...
await onSuccess;
expect(onSuccess).toHaveBeenCalledTimes(1);
...
like image 157
hipokito Avatar answered Nov 21 '25 06:11

hipokito



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!