I created custom plugin and i used ‘useTheme()’ function to build plugin content and custom editors using Grafana theme style.
There is any way to mock this call (‘useTheme()’) ?
I got the error below when i try to execute unit tests.
[INFO] TypeError: Cannot assign to read only property ‘constructor’ of object ‘#<Group>’
[INFO] > 4 | import { useTheme } from ‘@grafana /ui’;
[INFO] | ^
So just to make sure I understand - you want to mock useTheme
that you import from @grafana/ui
in your tests, right?
In that case, you can use jest.mock()
function.
Here is the example mocking getBackendSrv
function from @grafana/runtime
:
jest.mock('@grafana/runtime', () => ({
getBackendSrv: () => {
return {
get: () => {
return Promise.resolve([]);
},
};
},
}));
So in your case you want to mock just useTheme
, you can do something like this and add everything you need in useTheme
:
jest.mock('@grafana/ui', () => {
const original = jest.requireActual('@grafana/ui');
return {
...original,
useTheme: () => {
return {
name: 'Grafana Dark'
};
},
};
});
I’m trying to create unit test for my custom plugin and i got the ‘cannot assign …’ error.
I tried your solution but it is not working (see screenshot below), i’m still getting the same error.
Maybe it is not related to mocking ?!
Just to confirm, are you using useTheme
in functional component?
Yes,
For now, the code below working for me:
1 Like
Awesome! I am glad it works.