Vuex - rawModule is undefined moving from single to multiple modules - javascript

Moved my project from single module in vuex store to multiple following the documentation.
It states that the specific module should be accessed like so:
store.state.a // -> `moduleA`'s state
This is when accessing the state of a module. It fails to say how to access getters and mutations as well as the commands like 'commit' and 'replaceState' for a specific module so I made my own conclusion:
store.getters.a
store.mutations.a
store.a.commit()
store.a.replaceState()
1) Are those conclusions correct?
2) Using these I get a really general error message:
TypeError: rawModule is undefined
Here is my store.js:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
listingModule: listingModule,
openListingsOnDashModule: listingsOnDashModule,
closedListingsOnDashModule: listingsOnDashModule
}
})
const listingsOnDashModule = {...}
const listingModule = {...}
// their content hasn't changes since the single module approach.

This error:
TypeError: rawModule is undefined
is caused by trying to register undefined as a module, you are probably importing undefined by accident when registering the module.
As for the syntax store.state.a is correct. With the rest the .a should just be omitted unless you are explicitly defining a namespace.

Related

Vue Error: Uncaught TypeError: Super expression must either be null or a function

I have encountered error in my vue app when I try to access vuex store in my translation setup file.
Uncaught TypeError: Super expression must either be null or a function
My export looks like this:
src/store/index.ts
const store = new Vuex.Store({
modules: {
global: new GlobalModule<any>(),
},
})
export default store
My usage of it looks like this:
src/lang/setup.ts
import store from '#/store/index'
let defaultLocale = store.getters['global/profile'].lang
I need to access the store to get preferred language but I can't access it from this file.

vue-test-utils: could not overwrite property $route, this is usually caused by a plugin that has added the property as a read-only value

I've looked at other answers with this problem, and it seems to be caused by trying to import vue-router into the test. This however, is not the case for my problem. Here is my test code:
import { mount, shallowMount, createLocalVue } from '#vue/test-utils'
import ListDetails from '../components/homepage/ListDetails'
import EntityList from '../components/homepage/EntityList'
import BootstrapVue from 'bootstrap-vue'
import Vuex from 'vuex'
import faker from 'faker'
const localVue = createLocalVue()
localVue.use(Vuex)
localVue.use(BootstrapVue)
describe('ListDetails.vue', () => {
it('gets the correct page list when router list id param present', () => {
const selected_list = {
id: faker.random.number(),
name: faker.lorem.words(),
entries: []
}
testRouteListIdParam(selected_list)
})
})
Then in testRouteListIdParam, I have:
function testRouteListIdParam(selected_list) {
// just assume this sets up a mocked store properly.
const store = setUpStore(selected_list, true)
const $route = {
path: `/homepage/lists/${selected_list.id}`
}
const wrapper = mount(ListDetails, {
mocks: {
$route
},
store,
localVue
})
}
As soon as mount() happens, I get the error:
[vue-test-utils]: could not overwrite property $route, this is usually caused by a plugin that has added the property as a read-only value
Any ideas why this would be happening? Again, I'm not using VueRouter anywhere in the unit tests, so I'm not sure why I'm getting the error. Could it be BootstrapVue or Vuex that are messing things up?
So this is a bug with vue-test-utils. If you are using VueRouter anywhere (even if it's not used in any unit test), you will get the above error.
A work around is to use process.env.NODE_ENV in your unit tests and set it to 'test', and wherever you're using VueRouter, check process.env.NODE_ENV like so:
if (!process || process.env.NODE_ENV !== 'test') {
Vue.use(VueRouter)
}
at least until vue-test-utils bug is fixed, this should fix this problem
I think these docs are relevant to your situation:
Common gotchas
Installing Vue Router adds $route and $router as read-only properties on Vue prototype.
This means any future tests that try to mock $route or $router will fail.
To avoid this, never install Vue Router globally when you're running tests; use a localVue as detailed above.
The error you're seeing indicates that one of your components (and outside your test code) is installing VueRouter (e.g., Vue.use(VueRouter)).
To address the issue, search for the VueRouter installation in your component code path, including any of their imports, and refactor it so that the import is not required there. Typically, the installation of VueRouter exists only in main.js or its imports.
GitHub demo
I encountered this, and it was because I was importing vueRouter into a controller, outside of a vueComponent, where this.$router wasn't defined.
import router from '#/router';
router.push('/foo')
janedoe's answer can work but it's often risky to modify production code just to make some tests pass. I prefer to bypass the bug by doing this:
Run your test in watch mode
npx jest --watch src/components/Foo.test.ts
Locate Vue.use(VueRouter) in your code and diagnose what is the chain of components indirectly running the code by adding this just above
const error = new Error();
console.log(
error.stack
?.split('\n')
.filter((line) => line.includes('.vue'))
.join('\n'),
);
This logs a list of file path like
console.log
at Object.<anonymous> (/path/to/components/Bar.vue:1:1)
at Object.<anonymous> (/path/to/components/Foo.vue:1:1)
Chose a component in this list and, in your test file, mock it
jest.mock('/path/to/components/Bar.vue');

Jest vs React: module exports and "Jest encountered an unexpected token"

I am having problems getting React and Jest to work together which seems odd as I thought they both came from a similar origin. My issue is around the way that the class I'm testing is being exported.
I have an ArticleService class which I could use happily in React when it was exporting as default:
class ArticleService {
constructor(articles) {
this.articles = articles;
if (!this.articles) {
this.articles =
[//set up default data....
];
}
}
getAll(){
return this.articles;
}
}
//module.exports = ArticleService;//Need this for jest testing, but React won't load it
export default ArticleService;// Can't test with this but React will load it.
Here is how it is being called in my React app (from my HomeComponent):
import ArticleService from './services/xArticleService';
and is being used happily as
const articles = (new ArticleService()).getAll();
However my tests will not run. Here is my test with an import of the class file:
import ArticleService from "../services/xArticleService";
it('correctly gets all summaries', () => {
var summaries = getFakeSummaryList();
var testSubject = new ArticleService(summaries);
var actual = testSubject.getAll();
expect(actual.length).toEqual(10);
});
and I get
FAIL src/tests/ArticleService.test.js
Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
U:\...\src\tests\ArticleService.test.js:2
import ArticleService from "../services/xArticleService";
^^^^^^
SyntaxError: Unexpected token import
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
If (in the test) I swop
import ArticleService from "../services/xArticleService";
for
const ArticleService = require('../services/xArticleService');
and edit the export in xArticleService.js to
module.exports = ArticleService;//Need this for jest testing, but React won't load it
then the tests are executed but React will not load it:
Attempted import error: './services/xArticleService' does not contain a default export (imported as 'ArticleService').
I have a default set up, creating using create-react-app. I've not changed any .babelrc.
Can anyone see where I am going wrong?
Thanks
UPDATE:
I have made the changes to .babelrc suggested in the accepted answer to the possible duplicate of this but this has made no change to the output.

why is vuex store only available after setTimeout?

I have a lib which imports the vuex store
import {store} from "./index"
and that index file has an constant export like
export const store = new Vuex.Store({ ...
in the file I'm doing the import, I wanted to use something from the store after the import, but store was undefined.
if I wrapped my store access in a setTimeout like
setTimeout(()=>{
// use store normally now..
},0)
it works.
Why? I'm guessing this isn't specific to Vuex but I don't know why it's happening.
This is probably a case of circular dependency.
Circular dependencies compile in webpack, but you get bugs at runtime.
Assuming you have files A and B and the dep chain is like A -> B -> A, then when B tries to import A, it still hasn't got to export stuff (because import statements precede statements that aren't import statements).
So import default ./A from B immediately returns undefined.
So either: make the B export a function that is somehow called after the A export is called, or create a module C that both A and B depend on that somehow fixes this circular dependency.
I'm guessing you are loading things out of order or your setup is a little off.
I would try injecting the store into your Vue instance, then you can assume it will be available in all sub components.
main.js
import {store} from "./index"
new Vue({
el: '#app',
store,
render: h => h(App)
})
Now in any child components you will have access to your store via this.$store

How can I access angular-redux store from child module?

In my angular app I use angular-redux for application state management. In my main module I defined my redux store. Like this:
export class MainModule {
constructor(private ngRedux: NgRedux<MainAppState>,
private devTools: DevToolsExtension) {
let enhancers = [];
if (environment.production === false && devTools.isEnabled()) {
enhancers = [...enhancers, devTools.enhancer()];
}
this.ngRedux.configureStore(
reducer,
{} as MainAppState,
[],
enhancers);
}
}
I created new child module, which contains some components. These components should access to application state. In one of these components I access via #select to store, but this doesn't work. Here is how I access to store:
export function getLanguage(state: LanguageState) { return state.userLanguage; }
And this code I have in my ChildComponent class:
export class ChildComponent implements OnInit {
#select(getLanguage) savedUserLanguage$: Observable<LanguageState>;
// more code
}
How can I access to application state store from child modules? What should I import in child module? Will It be better to create own module only for redux store handling? Maybe I forgot something?
I use Angular v4 and #angular-redux/store v6.
I'd recommend creating a separate module that just contains your store, e.g. StoreModule. You can then import your StoreModule into all your child modules and access your store from there.
This is the way they go in the official example app:
StoreModule: https://github.com/angular-redux/example-app/blob/master/src/app/store/module.ts
Child Module: https://github.com/angular-redux/example-app/blob/master/src/app/elephants/module.ts
Component in child module: https://github.com/angular-redux/example-app/blob/master/src/app/elephants/page.ts
I was thinking about refactoring some ugly old JavaScript code that uses prototypal inheritance into an Angular 7+ project. I was asking myself pretty much the same question. Inspired by my udemy Angular course, I tried an experiment with a ngrx store and lazy loaded modules.
(Keep in mind that ngrx is SIMILAR to #angular-redux, but it's NOT the same thing. See https://ngrx.io/docs for details.)
Here it is.
I create the store in the main module with StoreModule.forRoot and in each lazy loaded module, I create a reference to the store with StoreModule.forFeature.
(See https://ngrx.io/api/store/StoreModule for details.)
When I dispatch actions on the store with the lazy loaded components, those actions (and corresponding reducers) seem to change the value to which the main app component subscribes.
Also, when I dispatch actions on the store with the main app component, those actions (and corresponding reducers) seem to change the value to which the lazy loaded components subscribe.
Also, it's hard to explain what I did in a simple 200-500 character block so I had to use a github project.

Categories

Resources