我的API使用@woocommerce/woocommerce-rest-api
软件包。我正在使用NextJS和React Redux。这是我的woocommerce配置:
import WooCommerceRestApi from '@woocommerce/woocommerce-rest-api';
export const wooApi = new WooCommerceRestApi({
url: 'MY_API_URL',
consumerKey: 'MY_CONSUMER_KEY',
consumerSecret: 'MY_CONSUMER_SECRET',
version: 'wc/v3',
queryStringAuth: true,
});
组件安装后,我立即调度了一个动作。
这是我在操作中使用API的方式:
export const fetchMainProductCategories = () => {
return async (dispatch: Dispatch) => {
try {
const response = await wooApi.get(`products/categories?hide_empty=true&parent=0`);
dispatch<FetchMainProductCategories>({
type: CategoryTypes.fetchMainProductCategories,
payload: response.data,
});
} catch (error) {
console.log(error);
}
};
};
到目前为止,这是我最初的测试语句,但我不起作用:
import React from 'react';
import '../../__mocks__/matchMedia';
import MockCategories from '../../__mocks__/mockCategories';
import { render, cleanup, logDOM } from '@testing-library/react';
import Index from '../../pages/index';
import Root from '../../Root';
import { wooApi } from '../../config';
jest.mock('../../config');
describe('Homepage', () => {
beforeEach(() => {
render(
<Root>
<Index />
</Root>
);
});
afterEach(cleanup);
it('loads Product Categories', async () => {
wooApi.get.mockResolvedValueOnce({
data: MockCategories,
});
logDOM();
// const list = await waitFor(() => screen.getByTestId('category-list'));
});
});
答案 0 :(得分:1)
您需要将GRANT ALL PRIVILEGES ON DATABASE "triviaDB" to devuser;
的{{1}}方法注册为模拟方法,同时保留get
的其他功能。即:
wooApi
答案 1 :(得分:0)
已编辑:不好,通过执行jest.spyOn(config.wooApi, 'get')
,我们只是在模拟单个实例的“ get”方法。以下修改后的代码应该可以使用
您还可以使用jest.spyOn
仅模拟如下所示的get方法
import * as config from '../../config'
jest.spyOn(WooCommerceRestApi.prototype, 'get')
WooCommerceRestApi.prototype.get.mockResolvedValue('...')