我有一个名为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}`);
});
});
我的测试中一直出现运行时错误:
如果我unmock
axios,那么错误就会消失,但这对我没有帮助,因为我希望axios被嘲笑!
此外,由于以下行,似乎发生了错误:
import { status } from '../ajax';
为什么Jest如此挣扎于axios。为什么只是导入我的status
函数导致此错误?我在这里做错了吗?
答案 0 :(得分: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