Jest Mocking Permissions of Expo TypeError: Cannot read property 'askAsync' of undefined - permissions

I'm mocking expo and the Permissions module, but when calling Permissions.AskAsync Permissions is undefined.
Problem looks like this question. Using Jest to mock named imports
Used the provided answer, but did not work.
I have mocked the axios, which works. Doing the same for the expo module does not work.
The function I want to test:
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});
};
The test:
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();
});
});
The mock I use for expo:
jest.mock('expo', ()=>({
Permissions: {
askAsync: jest.fn()
}
}))
and tried
(In file mocks/expo.js)
export default {
Permissions: {
askAsync: jest.fn(() => {
return "SOMETHING"
})
}
}
and tried
(In file mocks/expo.js)
jest.mock('expo', ()=>({
Permissions: {
askAsync: jest.fn()
}
}));
Error: "TypeError: Cannot read property 'askAsync' of undefined"
This error occures on line where Permissions.askAsyc is called. So Permissions is undefined. (Also checked it with console.log(Permissions)
I expected the instance.state("cameraPermission") to be falsy, but it crashes before it comes to that line.

Since expo change the packages to be import * as Permissions from 'expo-permissions';
You just need to create "mocks/expo-permissions.js" and have it has:
export const getAsync = jest.fn(permissions => Promise.resolve());
export const askAsync = jest.fn(permissions => Promise.resolve());

teerryn's answer is correct and is a good start. To add some more details:
Unless you've configured different roots for Jest, you should place your mock file in __mocks__/expo-permissions.js where __mocks__ is a directory at the same level as your node_modules folder. See Jest docs on mocking node modules.
The permissions argument being passed in will be undefined due to the way we're mocking the module, so you'll need to mock the permission types you want to use. Just need something simple like export const CAMERA_ROLL = 'camera_roll';
If you want to respond differently based on the permission type passed in (for example, allow Permissions.CAMERA but deny Permissions.CAMERA_ROLL and all other types), you can mock the implementation of the askAsync function. For example, your __mocks__/expo-permissions.js file would look like this:
export const CAMERA = 'camera';
export const CAMERA_ROLL = 'camera_roll';
export const askAsync = jest.fn().mockImplementation((permissionType) => {
const responseData = permissionType === CAMERA ? { status: 'granted' } : { status: 'undetermined' }; // you could also pass `denied` instead of `undetermined`
return Promise.resolve(responseData);
});

The problem is that you are handling async tests incorrectly (your checkPermission() function is async). There are several ways you can tell jest that you want to test an async function. Here are a few ways.
Here is a quick solution to your problem:
...
import { Permissions } from 'expo';
...
jest.mock('expo', () => ({
Permissions: {
askAsync: jest.fn(),
}
}));
...
describe("Test the Permission function", () => {
it('should return rejected permission.', () => {
Permissions.askAsync.mockImplementation( permission => { return {status: 'granted'}; } ); // if you want to add some sort of custom functionality
const wrapper = shallow(<Photo2/>);
const instance = wrapper.instance();
return instance.checkPermission().then(data => {
expect(instance.state("cameraPermission")).toBeFalsy();
});
});
});

Related

Effector: ".use argument should be a function" on attach

effector throws error ".use argument should be a function" at getCurrent (node_modules/effector/effector/region.ts:27:5) on attach method while testing.
I'm trying integration testing with mocking of some initial state.
//babel config
module.exports = (api) => {
if (api.env('test')) {
config.plugins.push([
'module-resolver',
{
root: ['.'],
alias: {
effector-react: 'effector-react/scope',
},
},
]);
}
return config;
};
//store.ts
export const getUsersFx = attach({
effect: getUsersOriginalFx,
source: [$clientId],
mapParams: (_, [clientId]) => ({
clientId
}),
});
//component.tsx
import { render } from '#testing-library/react';
import { Provider } from 'effector-react/scope'
describe('TestableComponent', () => {
test('should increment counter after click', () => {
const scope = fork()
const rendered = render(
<Provider value={scope}>
<TestableComponent />
</Provider>
);
})
})
I think the reason is that Effector mocks Effect and under the hood uses .use for effect callback mock. But then it change it to null or undefined and Effector throws error that fn in .use(fn) must be function
Effector mocks getUsersFx => getUsersFx.use(mockFn <- it's undefined i think).
Effector version: 22
Looks like the reason is multiple passes of effector/babel-plugin which you using for tests - error with attach is similiar:
https://github.com/effector/effector/issues/601
Multiple passes of babel-plugin will be supported in the next minor release of effector - for now you can check your babel configuration for duplicated usage of effector/babel-plugin

How to initialize manually next.js app (for testing purpose)?

I try to test my web services, hosted in my Next.js app and I have an error with not found Next.js configuration.
My web service are regular one, stored in the pages/api directory.
My API test fetches a constant ATTACKS_ENDPOINT thanks to this file:
/pages/api/tests/api.spec.js
import { ATTACKS_ENDPOINT } from "../config"
...
describe("endpoints", () => {
beforeAll(buildOptionsFetch)
it("should return all attacks for attacks endpoint", async () => {
const response = await fetch(API_URL + ATTACKS_ENDPOINT, headers)
config.js
import getConfig from "next/config"
const { publicRuntimeConfig } = getConfig()
export const API_URL = publicRuntimeConfig.API_URL
My next.config.js is present and is used properly by the app when started.
When the test is run, this error is thrown
TypeError: Cannot destructure property `publicRuntimeConfig` of 'undefined' or 'null'.
1 | import getConfig from "next/config"
2 |
> 3 | const { publicRuntimeConfig } = getConfig()
I looked for solutions and I found this issue which talks about _manually initialise__ next app.
How to do that, given that I don't test React component but API web service ?
I solved this problem by creating a jest.setup.js file and adding this line of code
First add jest.setup.js to jest.config.js file
// jest.config.js
module.exports = {
// Your config
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
};
AND then
// jest.setup.js
jest.mock('next/config', () => () => ({
publicRuntimeConfig: {
YOUR_PUBLIC_VARIABLE: 'value-of-env' // Change this line and copy your env
}
}))
OR
// jest.setup.js
import { setConfig } from 'next/config'
import config from './next.config'
// Make sure you can use "publicRuntimeConfig" within tests.
setConfig(config)
The problem I faced with testing with Jest was that next was not being initialized as expected. My solution was to mock the next module... You can try this:
/** #jest-environment node */
jest.mock('next');
import next from 'next';
next.mockReturnValue({
prepare: () => Promise.resolve(),
getRequestHandler: () => (req, res) => res.status(200),
getConfig: () => ({
publicRuntimeConfig: {} /* This is where you import the mock values */
})
});
Read about manual mocks here: https://jestjs.io/docs/en/manual-mocks
In my case, I had to:
Create a jest.setup.js file and
setConfig({
...config,
publicRuntimeConfig: {
BASE_PATH: '/',
SOME_KEY: 'your_value',
},
serverRuntimeConfig: {
YOUR_KEY: 'your_value',
},
});
Then add this in your jest.config.js file:
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],

How Test with Jest a function in the method "mounted" VueJS

I would to try call a function already mocked. I use vueJS for the frond and Jest as unit test. Below a example of my code. My purpose is to test the call of « anotherFunction". The first test is succeed , not the second.Thanks for help or suggestion
code vueJS:
mounted() {
this.myfunction();
}
methods: {
myfunction() {
this.anotherFunction();
}
}
Jest code:
describe('Home.vue', () => {
let wrapper = null;
const options = {
mocks: {
$t: () => 'some specific text',
},
methods: {
myFunction: jest.fn(),
},
};
it('Should renders Home Component', () => {
// Given
wrapper = shallowMount(Home, options);
// Then
expect(wrapper).toBeTruthy();
});
it('Should call anotherFunction', async (done) => {
// Given
wrapper.vm.anotherFunction = jest.fn().mockResolvedValue([]);
// When
await wrapper.vm.myFunction();
// THIS THE PROBLEM, myFunction is mocked and I can't call the function 'anotherFunction' inside...
// Then
// expect(wrapper.vm.anotherFunction).toHaveBeenCalled();
});
});
I was finding a good way to help you if this test case. So, I thought in something like the chuck code below:
import { mount } from '#vue/test-utils';
describe('Home', () => {
it('method calls test case', () => {
const anotherMethodMock = jest.fn();
wrapper = mount(Home, {
methods: {
anotherMethod: anotherMethodMock
}
});
expect(anotherMethodMock).toHaveBeenCalled();
});
});
But, the Jest threw the following exception:
[vue-test-utils]: overwriting methods via the methods property is deprecated and will be removed in the next major version. There is no clear migration path for themethods property - Vue does not support arbitrarily replacement of methods, nor should VTU. To stub a complex m ethod extract it from the component and test it in isolation. Otherwise, the suggestion is to rethink those tests.
I had the following insight, maybe, in this case, should be better to test the side effect of this anotherMethod calling. What does it change? Is something being shown to the user?
I believe that here we have started from the wrong concept.
I hope that this tip could be useful :)
As suggested by #Vinícius Alonso, We should avoid using methods and setMethods in our test cases because of it's deprecation. But you can still test the mounted lifecycle by mocking the functions that are being called during mount. So you can do something similar to below snippet.
describe('Mounted Lifecycle', () => {
const mockMethodOne = jest.spyOn(MyComponent.methods, 'methodOne');
const mockMethodTwo = jest.spyOn(MyComponent.methods, 'methodTwo');
it('Validate data and function call during mount', () => {
const wrapper = shallowMount(MyComponent);
expect(mockMethodOne).toHaveBeenCalled();
expect(mockMethodTwo).toHaveBeenCalled();
})
})
Do mount/shallowMount inside it only rather putting it outside of it as it was not working in my case. You can checkout more details on it if you want.

Mock Native Module Jest

In my React-Native application i wanna write some unit tests for my Native Libraries.
dataStorage.js
import RNDataStorage, {ACCESSIBLE} from "react-native-data-storage";
const dataStorage = {
setData: function (key, value) {
return RNDataStorage.set(key, value, {accessible: ACCESSIBLE.ALWAYS_THIS_DEVICE_ONLY})
.then(res => {
console.log(res);
return true;
})
},
}
export default dataStorage;
dataStorage.test.js
import dataStorage from '../../src/services/dataStorage'
jest.mock('react-native-data-storage', () => {
return {
RNDataStorage: {
set: jest.fn(),
}
};
});
it('Should return Access & RefreshToken', function () {
dataStorage.setData('John', 'Test');
});
When i run this setup i receive the error: TypeError: Cannot read property 'set' of undefined.
What is the correct way to mocks some modules? Thanks for any help
The module you are mocking is an ES6 module with a default export and a named export.
Mocking it like this should get your test running:
jest.mock('react-native-data-storage', () => {
return {
__esModule: true,
default: {
set: jest.fn(() => Promise.resolve('the response'))
},
ACCESSIBLE: {
ALWAYS_THIS_DEVICE_ONLY: true
}
};
});
Answer based on this post

Using Jest to mock named imports

I have a 'notifications.js' module that looks a bit like this:
import { Notifications, Permissions } from 'expo'
export function setLocalNotification(storage = AsyncStorage) {
return storage
.getItem(NOTIFICATION_KEY)
.then(JSON.parse)
.then(data => {
if (data === null) {
return Permissions.askAsync(
Permissions.NOTIFICATIONS
).then(({ status }) => {
if (status === 'granted') {
Notifications.cancelAllScheduledNotificationsAsync()
...etc.
In my test, I want to mock Permissions and Notifications so I can do something like this in notifications.spec.js:
import { setLocalNotification } from './notifications'
import mockAsyncStorage from '../mock/AsyncStorage'
it('correctly cancels pending notifications', done => {
setLocalNotification(mockAsyncStorage).then(done())
expect(Permissions.askAsync).toBeCalled()
expect(Notifications.cancelAllScheduledNotificationsAsync)
.toBeCalled()
})
I've tried various things using jest.mock and jest.setMock but I can't seem to get this working. How do I go about mocking these named imports in the desired way? For instance, I've tried this:
jest.setMock('Permissions', () => ({
askAsync: jest
.fn()
.mockImplementationOnce(() => ({ status: 'granted' }))
}))
But that doesn't work. It throws
'module Permissions cannot be found from notifications.spec.js'
And if I try to mock the entire expo module, the mocked functions expect().toBeCalled() returns false.
You have to mock the module 'expo'
jest.mock('expo', ()=>({
Permissions: {
askAsync: jest.fn()
}
}))