【问题标题】:mock a library and run unit test模拟一个库并运行单元测试
【发布时间】:2021-07-21 10:28:18
【问题描述】:

我正在尝试使用 jest 来模拟一个库。
函数“requestAuthorization”只是一个快速函数。库“my-health-library”使用本机模块来访问“requestAuthorization”方法。

测试文件:

import MyHealthLibrary, { type } from 'my-health-library';


jest.mock('my-health-library', () => {
    return {
      MyHealthLibrary: {
         __esModule: true,
          default: {
             requestAuthorization: jest.fn(() => Promise.resolve('the response')),
             type: type
                }
            };
          }
     });

it('Testing to see if Library works', () => {
    let read = [type.heartRate]
    let write = [type.heartRate]

    expect(MyHealthLibrary.requestAuthorization(read, write)).toBe(true)
  })


此测试一直失败,并显示 jest.mock() 的模块工厂不允许引用任何超出范围的变量。”
我可以模拟我的函数“requestAuthorization”但是我如何模拟类型???
“类型”只是一个枚举

export enum type {
  bodyMassIndex = 'HKQuantityTypeIdentifierBodyMassIndex', 
  heartRate = 'HKQuantityTypeIdentifierHeartRate', 
  bodyTemperature = 'HKQuantityTypeIdentifierBodyTemperature',  
  bloodPressureSystolic = 'HKQuantityTypeIdentifierBloodPressureSystolic', 
  bloodPressureDiastolic = 'HKQuantityTypeIdentifierBloodPressureDiastolic',  
  bloodGlucose = 'HKQuantityTypeIdentifierBloodGlucose'
}

【问题讨论】:

    标签: javascript react-native unit-testing testing jestjs


    【解决方案1】:

    根据the doc可以jest.requireActual('my-health-library')

    jest.mock('my-health-library', () => {
      const { type } = jest.requireActual('my-health-library');
      return {
        MyHealthLibrary: {
          __esModule: true,
          default: {
            requestAuthorization: jest.fn(() => Promise.resolve('the response')),
            type
          }
        };
      }
    });
    
    

    编辑:但是,鉴于您导入模块的方式 (import MHL, { type } from 'm-h-l'),我认为导出应该是:

    return {
      __esModule: true,
      default: {
        // the default export, i.e. the MyHealthLibrary object of your import statement
        requestAuthorization: jest.fn(() => Promise.resolve('the response'))
      },
      type // out of the default export, to import it as desconstructed { type }
    };
    

    【讨论】:

      猜你喜欢
      • 2020-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多