我正在使用Jest来测试使用axios进行一些api调用的服务中的功能。问题在于,Jest一直在调用实际的服务函数,而不是模拟的服务函数。这是所有代码:
测试:
// __tests__/NotificationService.spec.js
const mockService = require('../NotificationService').default;
beforeEach(() => {
jest.mock('../NotificationService');
});
describe('NotificationService.js', () => {
it('returns the bell property', async () => {
expect.assertions(1);
const data = await mockService.fetchNotifications();
console.log(data);
expect(data).toHaveProperty('data.bell');
});
});
模拟:
// __mocks__/NotificationService.js
const notifData = {
bell: false,
rollups: [
{
id: 'hidden',
modifiedAt: 123,
read: true,
type: 'PLAYLIST_SUBSCRIBED',
visited: false,
muted: false,
count: 3,
user: {
id: 'hidden',
name: 'hidden'
},
reference: {
id: 'hidden',
title: 'hidden',
url: ''
}
}
],
system: [],
total: 1
};
export default function fetchNotifications(isResolved) {
return new Promise((resolve, reject) => {
process.nextTick(() =>
isResolved ? resolve(notifData) : reject({ error: 'It threw an error' })
);
});
}
服务:
import axios from 'axios';
// hardcoded user guid
export const userId = 'hidden';
// axios instance with hardcoded url and auth header
export const instance = axios.create({
baseURL: 'hidden',
headers: {
Authorization:
'JWT ey'
}
});
/**
* Notification Service
* Call these methods from the Notification Vuex Module
*/
export default class NotificationService {
/**
* @GET Gets a list of Notifications for a User
* @returns {AxiosPromise<any>}
* @param query
*/
static async fetchNotifications(query) {
try {
const res = await instance.get(`/rollups/user/${userId}`, {
query: query
});
return res;
} catch (error) {
console.error(error);
}
}
}
我尝试了几种使用require而不是导入NotificationService的变体,但是它还给出了其他一些隐秘的错误...
我觉得我缺少一些简单的东西。
请帮助我:)
答案 0 :(得分:0)
问题在于Jest一直在调用实际的服务函数而不是模拟的服务函数。
babel-jest
吊车jest.mock
的调用使它们先于其他所有程序(甚至是import
调用)运行,但是吊车在代码块中是本地的在issue 2582中。
我觉得我缺少一些简单的东西。
将您的jest.mock
调用移到beforeEach
之外,它将被提升到整个测试的顶部,因此require
将返回您的模拟:
const mockService = require('../NotificationService').default; // mockService is your mock...
jest.mock('../NotificationService'); // ...because this runs first
describe('NotificationService.js', () => {
it('returns the bell property', async () => {
...
});
});