1
votes

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
1
Why you use await on the last 3 lines? Is your action async?AdriSolid
yes the action is async it is calling an api, I believe the await should be only in the first from the last 3 lines, to await until the action is processed. question editedRubenex

1 Answers

0
votes

What about mocking dispatch? Then call your action and check if was called, something like:

const dispatch = jest.fn();
await createProduct(productRequest, onSuccess, onError, "jwt")(dispatch);
expect(dispatch).toHaveBeenCalledTimes(1);
expect(dispatch).toHaveBeenCalledWith({"id": 1}, "jwt");