axios Jest Mock未按预期工作,引发错误

fzwojiic  于 2022-12-29  发布在  iOS
关注(0)|答案(1)|浏览(211)
const axios = "axios";

jest.mock(axios);

axios.get.mockImplementation((url) => {
    if(url === process.env.ENHANCED_CLAIM_STATUS_276_DETAILS){
        return Promise.resolve({ status: 200, data: claim_response_276 });
    }
    if(url === process.env.ENHANCED_VALUE_ADDS_277_DETAILS){
        return Promise.resolve({ status: 200, data: claim_response_277 });
    }
});

我尝试模拟API响应,但它抛出此错误:

**TypeError: Cannot read properties of undefined (reading 'mockImplementation')**
zpf6vheq

zpf6vheq1#

moduleName参数应为字符串。请参见API文档jest.mock(模块名称、工厂、选项)
工作示例:

import axios from "axios";

jest.mock('axios');

describe('74929332', () => {
  test('should pass', async () => {
    axios.get.mockImplementation((url) => {
      return Promise.resolve({ status: 200, data: 'claim_response_276' });
    });
    const result = await axios.get('http://localhost:3000/api')
    expect(result).toEqual({ status: 200, data: 'claim_response_276' })
  })
});

试验结果:

PASS  stackoverflow/74929332/index.test.js (14.419 s)
  74929332
    ✓ should pass (3 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        15.559 s

相关问题