gpt4 book ai didi

reactjs - 开 Jest jest.fn 它正在被调用,但期望失败

转载 作者:行者123 更新时间:2023-12-05 06:50:26 26 4
gpt4 key购买 nike

我是开 Jest 测试的新手,我写了下面的测试。我 Jest mock 了一个函数并将其作为参数传递。但是当运行测试时,在日志中我可以看到函数 onSuccess 被调用。但 expect 失败并出现代码下方的错误。

我应该如何断言调用了 onSuccess = jest.fn()?

测试

 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)
})

日志:

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

最佳答案

模拟 dispatch 怎么样?然后调用您的操作并检查是否被调用,例如:

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

关于reactjs - 开 Jest jest.fn 它正在被调用,但期望失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66392267/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com