Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何用JEST中的配置模拟API调用?_Reactjs_Unit Testing_Jestjs_Next.js - Fatal编程技术网

Reactjs 如何用JEST中的配置模拟API调用?

Reactjs 如何用JEST中的配置模拟API调用?,reactjs,unit-testing,jestjs,next.js,Reactjs,Unit Testing,Jestjs,Next.js,我正在为我的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_CO

我正在为我的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);
        }
      };
   };
export const fetchMainProductCategories=()=>{
返回异步(分派:分派)=>{
试一试{
const response=wait wooApi.get(`products/categories?hide_empty=true&parent=0`);
派遣({
类型:CategoryTypes.fetchMainProductCategories,
有效载荷:response.data,
});
}捕获(错误){
console.log(错误);
}
};
};
以下是我到目前为止的初步测试陈述,但我不工作:

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'));
    });
 });
从“React”导入React;
导入“../../\uuuuu mocks\uuuu/matchMedia”;
从“../../\u____/MockCategories”导入MockCategories;
从'@testing library/react'导入{render,cleanup,logDOM};
从“../../pages/Index”导入索引;
从“../../Root”导入根目录;
从“../../config”导入{wooApi};
jest.mock('../../config');
描述('主页',()=>{
在每个之前(()=>{
渲染(
);
});
每次之后(清理);
它('加载产品类别',异步()=>{
wooApi.get.mockResolvedValue一次({
数据:类别,
});
logDOM();
//const list=wait waitFor(()=>screen.getByTestId('category-list');
});
});

您需要将
wooApi
get
方法注册为模拟,同时保留
api
的其他功能。即:

import { wooApi } from '../../config'
import { fetchMainProductCategories } from '../where-it-is-defined'

// mark get method as jest mock
jest.mock('../../config', () => ({
   ...jest.requireActual('../../config'), // to avoid overriding other methods/features
   get: jest.fn(), // override get method of the api
}))

describe('Homepage', () => {
   beforeEach(()=>{
      wooApi.get.mockResolvedValue({
         status: 200,
         data: { categories: ['a', 'b'] },
   })

   test('loads ...', async () => {
   const dispatch = jest.fn()

   await fetchMainProductCategories()(dispatch)

   expect(dispatch).toHaveBeenCalledWith(
      { type: '...',
        payload: { categories: ['a', 'b'] }
      }
    )
   })
})
Ref:

编辑:我的坏,通过执行
jest.spyOn(config.wooApi,'get')
我们只是在模仿单个实例的“get”方法。下面编辑的代码应该可以工作

您还可以使用
jest.spyOn
来模拟get方法,如下所示

import * as config from '../../config'

jest.spyOn(WooCommerceRestApi.prototype, 'get')
WooCommerceRestApi.prototype.get.mockResolvedValue('...')

你对此有什么问题?当您测试fetchMainProductCategories时,您需要模拟wooApi.get,并且您需要在其他任何地方模拟fetchMainProductCategories,这是一个很好的单元测试策略。谢谢!我尝试了这个,得到了TypeError:_config.wooApi.get.mockResolvedValue不是一个函数-是的,我也尝试了这个,但仍然得到了相同的错误。非常感谢。