Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 我试图从服务中模拟函数,但Jest一直在调用实际函数而不是模拟函数_Unit Testing_Jestjs_Axios - Fatal编程技术网

Unit testing 我试图从服务中模拟函数,但Jest一直在调用实际函数而不是模拟函数

Unit testing 我试图从服务中模拟函数,但Jest一直在调用实际函数而不是模拟函数,unit-testing,jestjs,axios,Unit Testing,Jestjs,Axios,我正在使用Jest测试来自使用axios进行一些api调用的服务的函数。问题是Jest一直在调用实际的服务函数,而不是模拟的服务函数。以下是所有代码: 测试: // __tests__/NotificationService.spec.js const mockService = require('../NotificationService').default; beforeEach(() => { jest.mock('../NotificationService'); });

我正在使用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);
    }
  }
}
从“axios”导入axios;
//硬编码用户guid
export const userId='hidden';
//具有硬编码url和身份验证标头的axios实例
export const instance=axios.create({
baseURL:'隐藏',
标题:{
授权:
“JWT ey”
}
});
/**
*通知服务
*从通知Vuex模块调用这些方法
*/
导出默认类NotificationService{
/**
*@GET获取用户的通知列表
*@returns{axiopromise}
*@param查询
*/
静态异步获取通知(查询){
试一试{
const res=wait instance.get(`/rollups/user/${userId}`{
查询:查询
});
返回res;
}捕获(错误){
控制台错误(error);
}
}
}
我尝试了使用require而不是导入NotificationService的几种变体,但它给出了一些其他隐秘的错误

我觉得我错过了一些简单的事情

请帮帮我:)

问题是Jest一直在调用实际的服务函数,而不是模拟的服务函数

babel jest
提升
jest.mock
调用,以便它们在所有其他调用之前运行(甚至是
import
调用),但提升是代码块的本地操作,如中所述

我觉得我错过了一些简单的事情

在每次之前,将你的
jest.mock
调用移到
之外,它将被提升到整个测试的顶部,因此你的mock将由
require
返回:

const mockService=require('../NotificationService')。默认值;//mockService是您的模拟服务。。。
jest.mock(“../NotificationService”);/。。。因为这是第一个
description('NotificationService.js',()=>{
它('返回bell属性',async()=>{
...
});
});