简体   繁体   English

如何使用 jest 和 react 测试库测试 axios api?

[英]How to test axios api using jest and react testing library?

this is my apis.js where my axios logic is written这是我的 apis.js,我的 axios 逻辑写在这里

import axios from 'axios'

function logSuccess(req, res, next) {
  console.log(req, res)

  next(res)
}

function logError(req, res, e, next) {
  console.log(req, res, e)

  next(e)
}

function getResource(url, onComplete) {
  let _onSuccess = (res) => logSuccess(url, res, onComplete)
  let _onError = (res, e) => logError(url, res, e, onComplete)
  let _onException = (e) => logError(url, null, e, onComplete)

  axios
    .get(url)

    .then((res) => {
      res ? _onSuccess(res) : _onError(res)
    }, _onException)

    .catch(_onException)
}

function postResource(url, data, cancelTokenSource, onComplete) {
  let _onSuccess = (res) => logSuccess(url, res, onComplete)
  let _onError = (res, e) => logError(url, res, e, onComplete)
  let _onException = (e) => logError(url, null, e, onComplete)

  axios
    .post(url, data, { cancelToken: cancelTokenSource.token })

    .then((res) => {
      res ? _onSuccess(res) : _onError(res)
    }, _onException)

    .catch(_onException)
}

const apis = {
  getResource,
  postResource,
}

export default apis

this is my other file where i have called axios functions:这是我调用 axios 函数的另一个文件:

    import apis from '../../commonUtils/apis/apis'

export default class LookingGlassAPIs {
  constructor(params) {
    let { apiRoot } = params

    this.routers = {}
    this.commandRequests = {}

    this.routers.getAll = (...rest) =>
      apis.getResource(apiRoot + 'routers', ...rest)
    this.commandRequests.post = (...rest) =>
      apis.postResource(apiRoot + 'commandRequests', ...rest)
  }
}
 const apiRoot = 'http://127.0.0.1:8080/'

i am new to react i donot know to write test case for axios without hitting api.can any one please help me.url is defined in another file but for reference i have decalred here only.我是新来的反应我不知道为 axios 编写测试用例而不击中 api。任何人都可以帮助我。url 在这里只定义了另一个文件中的参考。 should i use axios.get.mockResolvedValue(data)???Is it right way??我应该使用 axios.get.mockResolvedValue(data)???是正确的方法吗?

As long as the functions you want to test don't return anything, you could test if they throw or no.只要您要测试的函数不返回任何内容,您就可以测试它们是否抛出。

You would need to spy your axios methods, mocking a return value (in this case a Promise), something like:您需要监视您的 axios 方法,mocking 返回值(在本例中为 Promise),例如:

import axios from 'axios';
    
beforeAll(() => {
  axios.get.mockImplementation(() => Promise.resolve('whatever-get'));
  axios.post.mockImplementation(() => Promise.resolve('whatever-post'));
});
    
afterAll(() => {
  jest.clearAllMocks();
});
    
test('get does not throw', () => {
  expect(getResource()).not.toThrow();
});
    
test('post does not throw', () => {
  expect(postResource()).not.toThrow();
});

You must mock axios and look if axios methods are called with the right parameters for example.例如,您必须模拟 axios 并查看是否使用正确的参数调用了 axios 方法。

apis.spec.js api.spec.js

import apis from './apis';

jest.mock('axios'); // This overwrites axios methods with jest Mock
import axios from 'axios';

describe('Test Apis', () => {
    describe('getResource', () => {
        describe('with success', () => {
            const url = 'http://test-url.com';
            const onComplete = jest.fn();
            const data = {};

            beforeEach(() => {
                axios.get.mockResolvedValue(data);
            });

            it('should call axios get with given url', () => {
                getResource(url, onComplete);
                expect(axios.get).toBeCalledWith(url);
            });

            it('should call onComplete callback with response', async () => { // do not forget 'async'
                await getResource(url, onComplete); // notice the 'await' because onComplete callback is called in '.then'
                expect(onComplete).toBeCalledWith(data);
            });
        });
    });
});

You could do the same with the error response and POST method.您可以对错误响应和 POST 方法执行相同的操作。 You could also test your LookingGlassAPIs by mocking your apis.js methods, or again by mocking axios , it depends of your "unit" definition inside your project.您还可以通过 mocking 您的LookingGlassAPIs方法或再次通过 mocking axios apis.js这取决于您在项目中的定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在反应测试库和笑话中测试 axios 请求 - How to test axios requests in react testing library and jest 使用 JEST 和 React 测试库在 Onclick Function 中测试 API 调用 - Test API call in Onclick Function using JEST and React Testing Library 如何使用 React、Jest 和 React-testing-library 为带有令牌的 api 调用编写单元测试? - How can I write unit test for api call with token using React, Jest and React-testing-library? 如何使用 jest 和 react 测试库在 react 中测试路由 - how to test Routes in react using jest and react testing library 使用 react-query 和 axios 测试 React 组件中的错误的问题。 使用 React 测试库、Jest、msw 进行测试 - Problem with testing for error in React component using react-query and axios. Test with React Testing Library, Jest, msw 如何使用 react-testing-library 和 jest 测试链接 - How to test link using react-testing-library and jest 如何使用 React 测试库和 jest 测试条件渲染的字符串 - How to test conditionally rendered string using React testing library and jest 我将如何使用 Jest 和 React 测试库对此进行测试? - How would I test this using Jest & React Testing library? 如何使用 Jest 和 React 测试库测试 className - How to test a className with the Jest and React testing library 使用 React 测试库/Jest 模拟 axios 帖子 - Mocking an axios post using React Testing Library / Jest
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM