【问题标题】:TypeError: moduleName.startsWith is not a function when mocking "axios"TypeError: moduleName.startsWith 不是模拟“axios”时的函数
【发布时间】:2022-01-29 00:50:38
【问题描述】:

我正在尝试模拟 axios get 函数,但在模拟“axios”时收到TypeError: moduleName.startsWith is not a function 模拟它的正确方法是什么?

错误:

 FAIL  src/tests/Sample.test.jsx
  ● Test suite failed to run

    TypeError: moduleName.startsWith is not a function

       5 | import { backendUrl } from "../helper/constants"
       6 | describe("test useEffect and axios", () => {
    >  7 |     const mockGet = jest.mock(axios.get)

Sample.test.jsx

import { mount } from "enzyme"
import { screen, render, act } from "@testing-library/react"
import Sample from "../pages/Sample"
import axios from "axios"
import { backendUrl } from "../helper/constants"
describe("test useEffect and axios", () => {
    const mockGet = jest.mock(axios.get) // THROWS ERROR HERE

    let wrapper
    it("should call axios", async () => {
        await act(async () => {
            mockGet.mockImplementationOnce(() => Promise.resolve({}))
            wrapper = mount(<Sample />)
        })
        wrapper.update()
        await expect(mockGet).toHaveBeenCalledWith(backendUrl)
    })
})

示例.jsx

import axios from "axios"
import { useState, useEffect } from "react"
import { backendUrl } from "../helper/constants"

const Sample = () =>{
    const [pets, setPets] = useState([])
    useEffect(() => axios.get(backendUrl)
    .then(({data}) =>setPets(data.entries))
    .catch((err)=>console.log(err)), [])
    return (
        <>
        <p>I h8 all of you</p>
            {pets.map((e, i) =><h2 key={i}>{e.Link}</h2>)}
        </>
    )
}

export default Sample

【问题讨论】:

    标签: javascript reactjs axios jestjs enzyme


    【解决方案1】:

    您必须使用正确的语法,例如jest.mock('axios'),所以在您的情况下:

    jest.mock('axios')
    
    describe("test useEffect and axios", () => {
        const mockGet = jest.fn()
    
        let wrapper
        it("should call axios", async () => {
            await act(async () => {
                mockGet.mockImplementationOnce(() => Promise.resolve({}))
                wrapper = mount(<Sample />)
            })
            wrapper.update()
            await expect(mockGet).toHaveBeenCalledWith(backendUrl)
        })
    })
    

    【讨论】:

    • 如果它适合你,你能把它标记为答案
    猜你喜欢
    • 2022-10-19
    • 1970-01-01
    • 2021-12-03
    • 2020-08-31
    • 2018-08-31
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多