3

我有一个名为的模块ajax.js,它为我导出了一堆 ajax 函数。我正在尝试用 Jest 测试以下功能:

export const status = ({loginUrl='/', logoutUrl='/'}) => {
  return axios.get(`/auth?login=${loginUrl}&logout=${logoutUrl}`);
};

我的测试如下所示:

jest.unmock('../ajax');

import { status } from '../ajax';

describe('ajax', () => {
  let urls;

  beforeEach(() => {
    urls = {
      loginUrl: '/',
      logoutUrl: '/'
    };
  });

  it('calls status with a login and logout url', () => {
    const { loginUrl, logoutUrl } = urls;

    status(urls);
    expect(axios.get).toBeCalledWith(`/auth?login=${loginUrl}&logout=${logoutUrl}`);
  });
});

我在测试中不断收到运行时错误:

运行时笑话错误

如果我unmockaxios,错误就会消失,但这对我没有帮助,因为我希望 axios 被嘲笑!

此外,由于这一行,错误似乎正在发生:

import { status } from '../ajax';

为什么 Jest 在 axios 上苦苦挣扎。为什么只是导入我的status函数会导致此错误?我在这里做错了吗?

4

1 回答 1

0

这是基于以下解决方案:

"jest": "^24.8.0",
"ts-jest": "^24.0.2",
"tslint": "^5.18.0",
"typescript": "^3.5.3"
"axios": "^0.19.0",
"@types/jest": "^24.0.17",

ajax.ts

import { status } from './ajax';
import axios from 'axios';

const originalGet = axios.get;
axios.get = jest.fn();

describe('ajax', () => {
  let urls;

  beforeEach(() => {
    urls = {
      loginUrl: '/',
      logoutUrl: '/'
    };
  });

  afterEach(() => {
    axios.get = originalGet;
  });

  it('calls status with a login and logout url', async () => {
    const { loginUrl, logoutUrl } = urls;
    (axios as jest.Mocked<typeof axios>).get.mockResolvedValueOnce('mocked data');
    const actualValue = await status(urls);
    expect(actualValue).toBe('mocked data');
    expect(axios.get).toBeCalledWith(`/auth?login=${loginUrl}&logout=${logoutUrl}`);
  });

  it('should restore original get', () => {
    expect(jest.isMockFunction(axios.get)).toBeFalsy();
  });
});

单元测试结果:

 PASS  src/stackoverflow/38129774/ajax.spec.ts
  ajax
    ✓ calls status with a login and logout url (7ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.906s, estimated 3s
于 2019-09-06T16:34:32.210 回答