Jest unable to load module vue-cookies - vue.js

console.error node_modules/vue/dist/vue.runtime.common.dev.js:621
[Vue warn]: Error in mounted hook (Promise/async): "TypeError: Cannot read property 'get' of undefined"
found in
---> <Anonymous>
<Root>
console.error node_modules/vue/dist/vue.runtime.common.dev.js:1884
TypeError: Cannot read property 'get' of undefined
at VueComponent.mounted (/home/ubuntu/vue-testing-skel/src/components/ChatApp.vue:66:1)
The line that is causing the error:
this.current_nickname = this.$cookies.get('nickname')
this.$cookies is provided by a module called vue-cookies
I have it installed and saved in my devDependencies, but it seems jest is unable to find it or load it.
I'm not sure what I have to do to make sure Jest is loading these modules properly.

Testing with Jest is meant to be self-contained. This means that global objects like this.$cookies are not available since they are interfacing with the cookies in your browser. The way to solve this is to mock the global functions. More info on how to do that here:
https://lmiller1990.github.io/vue-testing-handbook/mocking-global-objects.html#example-with-vue-i18n

To build off of #Imre_G 's answer, you need to specify a $cookies key inside your mount() or shallowMount() function, like so:
wrapper = shallowMount(ComponentName, {
localVue,
...
mocks: {
$cookies: {
get: jest.fn().mockReturnValue(null),
set: jest.fn(),
}
}
});

Related

Vue router return an error in mounted hook

I have an error with Vue-Router, when click to the route-link component wasn't loaded.
[Vue warn]: Error in mounted hook (Promise/async): "TypeError: Cannot read properties of >undefined (reading 'id')"
found in
at assets/organisms/manage/ManageWorkFlowOverview.vue
Do you have an idea of the origin of the problem ?
Thanks in advance.
Best regards,
Jérémy

As soon I add "props" to the component I get: Error in callback for watcher "function () { return this._data.$$state }"

I get a very strange error which I can't locate.
[Vue warn]: Error in callback for watcher "function () { return this._data.$$state }": "Error: [vuex] do not mutate vuex store state outside mutation handlers."
I am using vuex in strict mode. Despite the error I am not mutating any vuex store state outside mutation handlers. The component is not using vuex at all. I created a test component that does not use anything like below.
<template>
<div>
TEST COMPONENT
</div>
</template>
<script>
export default {
name: 'testComponent',
props: ['testProp'],
}
</script>
As soon I add the props part I get the error. I am not able to represent the whole project here or reproduce it. But there is nothing special anyway.
For me it was because I did routes = this.$router.options.routes for setting up Navigation.
The solution was routes = JSON.parse(JSON.stringify(routes)) before assigning routes to state.
Well after some debugging I found out that it actually was caused by vuex and vue-router.
Actually I could find this before if I just looked detailed into the trace of the error. The vue-router.esm.js?8c4f:2279 section was giving a hint but I could not see it (lack of vue experience I guess).
...
reactiveSetter # vue.runtime.esm.js?2b0e:1055
normalizeProps # vue.runtime.esm.js?2b0e:1449
mergeOptions # vue.runtime.esm.js?2b0e:1521
Vue.extend # vue.runtime.esm.js?2b0e:5159
extractGuard # vue-router.esm.js?8c4f:2279
eval # vue-router.esm.js?8c4f:2263
eval # vue-router.esm.js?8c4f:1968
eval # vue-router.esm.js?8c4f:1968
...
I was getting the the routes from the store and adding (addRoutes()) them to the route.
router.beforeEach((to, from, next) => {
...
router.addRoutes([store.getters['route/getRoute']]);
...
}
But because it was passed by reference (and I guess the router was doing some changes on it) the error was rising. The route was trying to "mutate vuex store outside mutation hander"
[Vue warn]: Error in callback for watcher "function () { return
this._data.$$state }": "Error: [vuex] do not mutate vuex store state outside
mutation handlers."
I solved it by deep cloning (like below) it with lodash but could use other deepcloning as well.
let routeDeepClone = _.cloneDeep([store.getters['route/getRoute']]);
router.addRoutes(routeDeepClone);
Now it works very well. Hope it helps someone.
I was dumbfounded by this for a little while, but turns out it was something super silly. As the error suggests, we are modifying a Vuex state somewhere inadvertently. Possibly, you are doing an assignment without realizing it. My error was this:
computed: {
foo() {
return this.model.bar.find(
(obj) => obj.key = this.$route.params.baz
)
},
}
Silly me, I was doing
obj.key = this.$route.params.baz
instead of
obj.key === this.$route.params.baz
The object was getting updated by reference instead of my intention of doing an equality check.

cannot read property 'data' undefined

I am trying to get ag-grid row data for editing in a modal window.
during render vue throughs the bellow error.
[Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'data' of undefined"
my code. This is the mounted method.
mounted() {
this.leadsData = JSON.parse(JSON.stringify(this.params.data))
},
this.params must be a variable present in the data function,
otherwise, if you look for a property in the url you can use
this.$route.params.data or this.$route.query.data

Mocha / jsdom "SecurityError: localStorage is not available for opaque origins"

I get this error when testing with Mocha and jsdom my Vue components and using localStorage in them:
[Vue warn]: Error in data(): "SecurityError: localStorage is not available for opaque origins"
All the issues I could find on Github or here do reference to Jest and the solutions suggest to set the Jest config option testUrl to any valid URL. But how to set it directly on the jsdom instance?
When I add an options object when initialising jsdom - nothing happens:
let jsdom = require('jsdom-global')(
{
url: "https://dev.wue-theme.test"
}
);
Ok, looking into jsdom's index.js helped - the first parameter is expecting an HTML string or undefined to set a default HTML string/wrapper, the options object goes as the second parameter:
let jsdom = require('jsdom-global')(
undefined,
{
url: "https://dev.wue-theme.test"
}
);
Now when running mocha test the error has gone indeed

angular2 testing, error in ViewUtils when using setBaseTestProviders()

When using the method 'setBaseTestProviders(..)', an error pops up in the console.
We're using angular-2.0.0-rc.1.
The test (test/areas-list.component.spec.ts) is as follows:
import {setBaseTestProviders} from "#angular/core/testing";
import {ADDITIONAL_TEST_BROWSER_PROVIDERS, TEST_BROWSER_STATIC_PLATFORM_PROVIDERS} from '#angular/platform-browser/testing/browser_static';
import {BROWSER_APP_DYNAMIC_PROVIDERS} from '#angular/platform-browser-dynamic';
setBaseTestProviders([
BROWSER_APP_DYNAMIC_PROVIDERS,
ADDITIONAL_TEST_BROWSER_PROVIDERS,
], TEST_BROWSER_STATIC_PLATFORM_PROVIDERS);
describe('test test', () => {
//Not really important
});
When I open the browser, the following error is shown in the console:
zone.js:323 Error: Error: Cannot resolve all parameters for 'ViewUtils'(RootRenderer, undefined #Inject(Token AppId), SanitizationService). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'ViewUtils' is decorated with Injectable.
at NoAnnotationError.BaseException [as constructor] (http://127.0.0.1:8080/node_modules/#angular/core/src/facade/exceptions.js:17:23)
at new NoAnnotationError (http://127.0.0.1:8080/node_modules/#angular/core/src/di/reflective_exceptions.js:217:16)
at _extractToken (http://127.0.0.1:8080/node_modules/#angular/core/src/di/reflective_provider.js:232:15)
at eval (http://127.0.0.1:8080/node_modules/#angular/core/src/di/reflective_provider.js:184:45)
at Array.map (native)
at _dependenciesFor (http://127.0.0.1:8080/node_modules/#angular/core/src/di/reflective_provider.js:184:19)
at resolveReflectiveFactory (http://127.0.0.1:8080/node_modules/#angular/core/src/di/reflective_provider.js:72:24)
at resolveReflectiveProvider (http://127.0.0.1:8080/node_modules/#angular/core/src/di/reflective_provider.js:96:97)
at Array.map (native)
at Object.resolveReflectiveProviders (http://127.0.0.1:8080/node_modules/#angular/core/src/di/reflective_provider.js:104:31)
Evaluating http://127.0.0.1:8080/test/areas-list.component.spec.js
Error loading http://127.0.0.1:8080/test/areas-list.component.spec.js
Does somebody know what the problem is? Thanks in advance!
Is there any specific case you're trying to achieve with browser static?
Here is the basic config:
import { setBaseTestProviders } from '#angular/core/testing';
import {
TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS,
TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS,
} from '#angular/platform-browser-dynamic/testing';
setBaseTestProviders(TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS, TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS);