Javascript 模拟库并运行单元测试
我试图用笑话来模仿图书馆。Javascript 模拟库并运行单元测试,javascript,react-native,unit-testing,testing,jestjs,Javascript,React Native,Unit Testing,Testing,Jestjs,我试图用笑话来模仿图书馆。 函数“requestAuthorization”只是一个swift函数。库“我的健康库”使用本机模块访问“requestAuthorization”方法。 测试文件: import MyHealthLibrary, { type } from 'my-health-library'; jest.mock('my-health-library', () => { return { MyHealthLibrary: { __
函数“requestAuthorization”只是一个swift函数。库“我的健康库”使用本机模块访问“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'
}
根据您可以jest.requirectual('my-health-library')
:
jest.mock('my-health-library',()=>{
const{type}=jest.requireActual('my-health-library');
返回{
MyHealthLibrary:{
__艾斯莫杜勒:没错,
默认值:{
requestAuthorization:jest.fn(()=>Promise.resolve(“响应”),
类型
}
};
}
});
编辑:但是,考虑到您导入模块的方式(import MHL,{type}来自'm-h-l'
),我认为导出应该是:
返回{
__艾斯莫杜勒:没错,
默认值:{
//默认导出,即导入语句的MyHealthLibrary对象
requestAuthorization:jest.fn(()=>Promise.resolve('response'))
},
在默认导出中键入//以将其作为Deconstructed{type}导入
};