我很难在我的thunk中模拟API响应。模拟返回未定义的数据。
错误:预期为(jest.fn()).toHaveBeenCalledWith(预期为...)
预期:{“有效负载”:{“数据”:[“嘿”,“foo”],“结果值”:0},“类型”:“产品/集产品”}
接收到1个对象{ -“有效负载”:对象{ -“数据”:数组[ -“嘿”,-“foo”,- ],-“结果值”:0,+“ meta”:对象{ +“参数”:未定义,+“请求ID”:“xwidHSyGluO 0 zxXJgYNC”,+“请求状态”:“挂起”、}、-“类型”:“产品/集合产品”,+“有效负载”:未定义,+“类型”:“产品/获取产品/待处理”,},2对象{ -“有效负载”:对象{ -“数据”:数组[ -“嘿”,-“foo”,- ],-“结果值”:0,- },-“类型”:“产品/集合产品”,+“有效负载”:未定义,+“类型”:“产品/集合获取”,},
具有方法的API文件对象
import { instance } from "./index";
import { ProductType } from "../types/ProductType";
export const productsApi = {
requestProducts() {
return instance.get<ProductType[]>('products')
.then(response => response.data)
},
}
感谢
export const getProducts = createAsyncThunk<void, void>
("products/getProducts",
async function (_, { dispatch }) {
dispatch(setFetching())
try {
const response = await productsApi.requestProducts() `Here is problem with mocking, returns undefined`
dispatch(setProducts(response))
} catch {
dispatch(setError('Some error has been occurred'))
} finally {
dispatch(setFetching())
}
});
测试
import productsSlice, {
getProducts,
productsSelector,
ProductsStateType,
setError,
setFetching,
setProducts
} from "./productsSlice";
import { RootState } from "../redux-store";
import { productsApi } from "../../api/products-api";
jest.mock("../../api/products-api")
const productsApiMock = productsApi as jest.Mocked<typeof productsApi>;
const dispatchMock = jest.fn();
const getStateMock = jest.fn();
beforeEach(() => {
dispatchMock.mockClear();
getStateMock.mockClear();
productsApiMock.requestProducts.mockClear();
});
const result = {
resultValue:0,
data: ['hey','foo']
}
productsApiMock.requestProducts.mockReturnValueOnce(Promise.resolve(result));
describe("products reducer thunk", () => {
it("getProducts thunk success ", async () => {
const thunk = getProducts();
thunk(dispatchMock, getStateMock, {});
expect(dispatchMock).toBeCalledTimes(2);
expect(dispatchMock).toHaveBeenCalledWith(setProducts(result));
});
});
1条答案
按热度按时间slhcrj9b1#
我也遇到了同样的问题。在测试回调中移动带有.mockReturnValueOnce的行对我有帮助。