Fix test false passes on unmocked requests

This commit is contained in:
Martin Hanzel 2019-08-15 14:04:43 -04:00
parent 663b7bb477
commit be6f20d54f
4 changed files with 21 additions and 8 deletions

View file

@ -6,9 +6,10 @@ axios.isMock = true;
axios.defaults.adapter = config => {
const message =
`Unexpected unmocked request: ${JSON.stringify(config, null, 2)}\n` +
'Consider using the `axios-mock-adapter` in tests.';
'Consider using the `axios-mock-adapter` module in tests.';
const error = new Error(message);
error.config = config;
global.fail(error);
throw error;
};

View file

@ -1,4 +1,4 @@
/* eslint-disable global-require, promise/catch-or-return */
/* eslint-disable global-require */
import path from 'path';
@ -126,9 +126,8 @@ describe('mocks_helper.js', () => {
it('survives jest.isolateModules()', done => {
jest.isolateModules(() => {
const axios2 = require('~/lib/utils/axios_utils').default;
expect(axios2.get('http://gitlab.com'))
.rejects.toThrow('Unexpected unmocked request')
.then(done);
expect(axios2.isMock).toBe(true);
done();
});
});

View file

@ -4,9 +4,11 @@ const $ = jest.requireActual('jquery');
// Fail tests for unmocked requests
$.ajax = () => {
throw new Error(
const err = new Error(
'Unexpected unmocked jQuery.ajax() call! Make sure to mock jQuery.ajax() in tests.',
);
global.fail(err);
throw err;
};
// jquery is not an ES6 module

View file

@ -3,11 +3,22 @@ import axios from '~/lib/utils/axios_utils';
describe('Mock auto-injection', () => {
describe('mocks', () => {
it('~/lib/utils/axios_utils', () =>
expect(axios.get('http://gitlab.com')).rejects.toThrow('Unexpected unmocked request'));
let failMock;
beforeEach(() => {
failMock = jest.spyOn(global, 'fail').mockImplementation();
});
it('~/lib/utils/axios_utils', done => {
expect(axios.get('http://gitlab.com')).rejects.toThrow('Unexpected unmocked request');
setImmediate(() => {
expect(failMock).toHaveBeenCalledTimes(1);
done();
});
});
it('jQuery.ajax()', () => {
expect($.ajax).toThrow('Unexpected unmocked');
expect(failMock).toHaveBeenCalledTimes(1);
});
});
});