permissions - 开 Jest mock Expo TypeError : Cannot read property 'askAsync' of undefined的权限

标签 permissions mocking jestjs expo

我正在 mock expo 和 Permissions 模块,但是在调用 Permissions.AskAsync Permissions 时未定义。

问题看起来像这个问题。 Using Jest to mock named imports

使用了提供的答案,但不起作用。

我 mock 了 axios,它有效。对 expo 模块执行相同的操作不起作用。

我要测试的功能:

    checkPermission = async () => {


        const {statusCamera} = await Permissions.askAsync(Permissions.CAMERA);

        // console.log(statusCamera);

        this.setState({cameraPermission: statusCamera});

        const {statusCameraRoll} = await Permissions.askAsync(Permissions.CAMERA_ROLL);
        this.setState({cameraRollPermission: statusCameraRoll});
    };

测试:

describe("Test the Permission function", () => {
    it('should return rejected permission.', async function () {
        const wrapper = shallow(<Photo2/>);
        const instance = wrapper.instance();

        await instance.checkPermission();

        expect(instance.state("cameraPermission")).toBeFalsy();
    });
});

我用于博览会的模拟:

jest.mock('expo', ()=>({
  Permissions: {
     askAsync: jest.fn()
  }
}))

并尝试过 (在文件 mocks/expo.js 中)

export default {
    Permissions: {
        askAsync: jest.fn(() => {
            return "SOMETHING"
        })

    }
}

并尝试过 (在文件 mocks/expo.js 中)

jest.mock('expo', ()=>({
    Permissions: {
        askAsync: jest.fn()
    }
}));

Error: "TypeError: Cannot read property 'askAsync' of undefined"

此错误发生在调用 Permissions.askAsyc 的行上。所以权限是未定义的。 (还用 console.log(Permissions)

检查了它

我预计 instance.state("cameraPermission") 是假的,但它在到达该行之前崩溃了。

最佳答案

自从世博会将软件包更改为import * as Permissions from 'expo-permissions';

您只需要创建“mocks/expo-permissions.js”并让它具有:

export const getAsync = jest.fn(permissions => Promise.resolve());
export const askAsync = jest.fn(permissions => Promise.resolve());

关于permissions - 开 Jest mock Expo TypeError : Cannot read property 'askAsync' of undefined的权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56441730/

相关文章:

java - 为什么我的应用程序中没有设置 AndroidManifest 权限

php - Laravel 5 中间件 "Owner"?

ios - 在 iOS 8 中呈现相机权限对话框

python - 如何模拟线程中的内置模块

javascript - 开 Jest 等到 typemoq 函数被调用

javascript - 从 JSON 比较中排除丢失的键

node.js - Node.js插件权限

mocking - 如何模拟@ngrx/store?

javascript - 如何测试您无权直接访问的功能

web-services - 如何对使用 Web 服务的类进行单元测试?