简体   繁体   English

使用 Axios 单元测试 NodeJs 控制器

[英]Unit Testing NodeJs Controller with Axios

I have a controller and a request file that look like this, making the requests with axios(to an external API), and sending the controller response to somewhere else, my question is, how to apply Unit Testing to my controller function (getInfoById), how do I mock the axiosRequest since it's inside the controller?.我有一个控制器和一个看起来像这样的请求文件,使用 axios(到外部 API)发出请求,并将控制器响应发送到其他地方,我的问题是,如何将单元测试应用于我的控制器功能(getInfoById) ,我如何模拟 axiosRequest 因为它在控制器内部? I am using Jest and only Jest for testing(might need something else, but I'm not changing)我正在使用 Jest 并且只使用 Jest 进行测试(可能需要其他东西,但我没有改变)

file: axiosFile.js

  import axios from "axios"

  export const axiosRequest = async (name) => {
    const { data } = await axios.get("url")
    return data
  }


file: controllerFile.js

  import { axiosRequest } from "./axiosFile"

  export const getInfoById = async (name) => {
    try {
      const response = await axiosRequest(name)
      return { status: 200, ...response }
    } catch {
      return { status: 500, { err: "Internal ServerError" } }
    }
  }

Thanks in advance.提前致谢。 PS: It's a Backend in NodeJs PS:它是 NodeJs 中的后端

You can mock the http calls using nock您可以使用nock模拟 http 调用

This way you will be directly able to test your method by mocking the underlying http call.这样你就可以通过模拟底层的 http 调用直接测试你的方法。 So in your case something like所以在你的情况下像

const nock = require('nock')

const scope = nock(url)
  .get('/somepath')
  .reply(200, {
    data: {
      key: 'value'
    },
  })

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM