Cannot use import statement outside a module - Vuex testing quasar - unit-testing

how are you ?
I'm having a issue in testing Vuex stuff with Quasar.
Testing components is working normally, but when I started to test my store, I got it.
spec file:
/test/jest/__tests__/store/auth/mutations.spec.js
import { store } from 'src/store';
import { mutations } from 'src/store/auth';
import mutations from 'src/store/auth/mutations';
All those ways I tried to import my store stuff, I got this error:
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { store } from 'quasar/wrappers';
SyntaxError: Cannot use import statement outside a module
how can I import my store in my spec files?

import { store } from 'src/store';
import { mutations } from 'src/store/auth';
import mutations from 'src/store/auth/mutations';
just use require
const store = require('src/store');
const mutations = require('src/store/auth)';
const mutations = require('src/store/auth/mutations');
you need
type=module in package.json to use import

Your problem is that import statements are not supported by plain JavaScript, therefore neither by Node. import is an addition called ES Modules. Since Jest runs your tests in Node, you are getting SyntaxError since import { store } from 'quasar/wrappers' is invalid JS syntax.
The solution is that you need to tell Jest to use Babel (or similar tool) to transform your test file before trying to execute it in Node.
This requires some configuration in your jest.config.js, and also you'd need to install babel-jest, babel and related packages and create a .babelrc or babel.config.js to tell Babel what to do with your test files exactly.
The actual right configuration may depend on many factors, but as a starting point refer to these:
https://jestjs.io/docs/en/getting-started#using-babel
https://jestjs.io/docs/en/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object
https://github.com/facebook/jest/tree/master/packages/babel-jest#setup
Also I'd recommend to consider using Quasar CLI, which gives you a handy way to automatically set up Jest for your Quasar project, including a simple example test you can use as a starting reference: https://testing.quasar.dev/

Related

How to use vuei18n-po?

i can't find a tutorial how to use package vuei18n-po in vue main.ts.
Yts documentation is small, and not well descriped.
https://www.npmjs.com/package/vuei18n-po.
I have never use something like this inside app initiation in vue, so it is realy hard.
it is my code:
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import "jquery";
import "bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
import vuei18nPo from "vuei18n-po";
const app = createApp(App);
await vuei18nPo({
po: ["django.po", "../../backend/locale/pl/LC_MESSAGES/django.po"],
messagesFile: "generated/allInOne.json",
messagesDir: "generated",
});
app.use(router);
app.mount("#app");
In my code i did not use plug it in option, because i wanted to generate it first.
EDIT
I found this error on localhost
Module "fs" has been externalized for browser compatibility. Cannot
access "fs.realpath" in client code.
I dont understand what this mean too.
I don't think that this package is meant to be used for client side code regarding the error especially because po is a GUI-based solution.
The vuei18n-po is meant to transform some files locally with some JS backend like a Node.js app (this is the Usage part in package's README).
Then for the 2nd part (Plug it in), you could use the generated files with an i18n setup for VueJS with the regular Vue2 package for i18n: https://kazupon.github.io/vue-i18n/
Or the one for Vue3: https://vue-i18n.intlify.dev/
If it's not clear enough, feel free to read articles on how to setup i18n with Vue.
This is then a 2 step problem. I recommend that you start with a simple example of 2 small JSON files in Vue, then that you try to convert your .po files with the vuei18n-po package.

Is there any "ember-moment-shim" alternative for dayJS?

ember-moment-shim is an ember addon that generates the locales conditionally based on Moment.js and Moment-Timezone.
Any tools or processes to accomplish the same with just DayJs instead.
Ref: https://github.com/jasonmit/ember-cli-moment-shim
UPDATE:
I want to lazy load or dynamically load the dayJs locales based on the requirement. And every time you need to load a locale, you need to import it like
import fr from 'dayjs/locale/fr'
just that it would be a different locale every time and could change on refresh based on the settings from API response.
ember-auto-import throws following Error
Uncaught SyntaxError: Cannot use import statement outside a module*
Addons like ember-cli-moment-shim are no longer required to use libraries from NPM instead you can use them directly after installing ember-auto-import.
From the command line do:
ember install ember-auto-import
npm install dayjs
Then you can just import dayjs where you need it.
For example in a component:
//app/components/today.js
import dayjs from 'dayjs';
import Component from '#glimmer/component';
export default class TodayComponent extends Component {
today = dayjs().format();
}

Global beforeEach/afterEach for ember qunit tests

My app stores some information about the current session in localStorage. Therefore I need my tests to clear localStorage before or after each single test throughout all test files. Is there a way to define a beforeEach or afterEach callback globally instead of on each test file?
We had wrapped ember-qunit's module, moduleFor and moduleForComponent for a nearly the same reason. And we are importing those wrappers instead of ember-qunit.
Another suggestion is to wrap localStorage with a service. Never access to localStorage except this service. So you can use a mock implementation of it in tests.
Updated:
How it is realised:
import { moduleFor, moduleForModel, test, only, setResolver } from 'ember-qunit';
import { moduleForComponent as qunitModuleForComponent } from 'ember-qunit';
function moduleForComponent(name, description, callbacks) {
//our implementation that wraps "qunitModuleForComponent"
//eg. init commonly used services vs.
}
export {
moduleFor,
moduleForComponent,
moduleForModel,
test,
only,
setResolver
};
Pros:
Prevents code duplication
Centralize unit test management
Easy to add new methods for custom needs, such as: moduleForValidatableComponent, moduleForLocalStorage
Cons:
ember-cli generates tests those are importing ember-qunit. Developers must change the import statements to these wrappers. It was sometimes forgotten. (When a test fails, developers remember that they need to change import statements.)
For some tests, wrapping is unnecessary.

Jasmine Spec as Typescript File

I'm attempting to set up unit testing in my project, using Jasmine. I am writing my specs in Typescript. My first test is simply checking that a config file returns a value as expected. However, when I import the config, Jasmine can't find the spec. If I take out the import and fill in dummy values, everything works fine.
My spec file is:
/// <reference path="../typings/index.d.ts"/>
process.env.ENV = "test";
process.env.TEST_DB_NAME= "test";
import environment = require("../config/config");
describe("Config Tests:", () => {
it("db returns string", () => {
expect(environment.db).toEqual(process.env.TEST_DB_NAME);
});
});
environment.db should simply return my process.env.TEST_DB_NAME.
I feel this has to do something with the import at the beginning making Jasmine not find the describe(). Anyone know of a way to get Jasmine to work with imports or am I just going about testing this the wrong way?
If you call require directly in your file I think you need to create a module and export it. Another way that I have used import successfully has been to create an interface, export it, and then did something like this.
import IUser = UserList.Interfaces.IUser;
You can then use this as the type for a mock object.

Dynamic module import in Ember CLI

I have a bunch of modules defined in an Ember CLI app and each starts with the same path. I would like to import the modules into a module in the app. For example, I could write:
import post1 from 'posts/1';
import post2 from 'posts/2';
import post3 from 'posts/3';
export default Em.ObjectController.extend({
posts: Em.A(post1, post2, post3),
});
However, I do not know the module names because they are created/named on the fly by a precompiler. All I know is that the path always begins with the same string. In this case, posts.
Is there a way to import all modules that begin with a particular path? For example, how can I do something like the following:
import posts from 'posts/*';
// or
registry['posts'].forEach(postId, i) {
var path = 'posts/' + postId;
import i from path;
}
Each of the modules I want to find and import has exported an object.
I have been through the ES6 module transpiler docs but can't find much.
The ES6 spec doesn't allow you to dynamically import modules using the import keyword. All importing and exporting using the module syntax must be done statically. However, it does provide a programmatic API that you can use to dynamically import modules. This article has a great summary of it (as well as a great summary of the rest of ES6 modules).
My suggestion would be to wrap Ember's loader API in a ES6 compliant wrapper. For instance, Ember-CLI uses the require() function to get modules, so you could do something like this:
window.System = window.System || {};
window.System['import'] = function(moduleName) {
return Ember.RSVP.Promise.resolve(window.require(moduleName));
}
// ...
System.import('my-app/posts/' + postNumber).then(function(postModule) {
// ...
});
You could also use the Ember require() function directly, my way just protects you in the likely event that Ember changes their module loader.