Angular-Ladda not working properly with browserify-shim / browserify - angularjs

I have installed angular-ladda using browserify-shim / browserify, but am unable to get the buttons to work properly. When I click on the button, the spinner is outside of the button, not matter which data-style I use.
You can find the instructions to browserify install here, but they did not work as I hoped. I ended using the information on this issue on GitHub to help me out, but I'm not sure that I did it correctly.
My app dependencies look like this:
require('angular').module('admin', [
require('Spinner'),
require('Ladda'),
require('angular-ladda')
])
My package.json file dependencies look like this:
"dependencies": {
"aliasify": "^2.0.0",
"angular": "^1.5.7",
"angular-bootstrap-show-errors": "^2.3.0",
"angular-breadcrumb": "^0.4.1",
"angular-cookies": "^1.5.7",
"angular-ladda": "^0.4.2",
"angular-ui-router": "^0.3.1"
}
"browser": {
"angular": "./node_modules/angular/angular.js",
"angular-breadcrumb": "./node_modules/angular-breadcrumb/release/angular-breadcrumb.js",
"spin.js": "./node_modules/angular-ladda/node_modules/js/spin.js"
}
"browserify-shim": {
"angular": {
"exports": "angular"
},
"angular-ladda": {
"depends": [
"ladda"
]
},
"ladda": {
"exports": "Ladda",
"depends": [
"spin.js"
]
},
"spin.js": {
"exports": "Spinner"
}
}
This is a gif of what the final result looks like: http://recordit.co/g2CmpETMC5.gif

What I did not realize is that with browserify-shim, you still have to link the style sheet. In my case, I had to compile the css file into a less file using:
#import (less) "/node_modules/angular-ladda/node_modules/ladda/dist/ladda-themeless.min.css";

Related

Why isn't ts-jest loading my custom tsconfig file?

For some reason, my custom tsconfig file isn't being picked up in jest.config.ts. Here is my jest.config.ts:
module.exports = {
setupFilesAfterEnv: [`./jest.setup.ts`],
testEnvironment: `jsdom`,
roots: [
`<rootDir>/test`
],
testMatch: [
`**/__tests__/**/*.+(ts|tsx|js)`,
`**/?(*.)+(spec|test).+(ts|tsx|js)`
],
transform: {
"^.+\\.(ts|tsx)$": `ts-jest`
},
globals: {
"ts-jest": {
tsConfig: `tsconfig.jest.json`
}
}
}
I know that other parts of this config ARE being applied. For example, if I remove the keys above globals my tests don't run. Also, I know that the change specified in my tsconfig.jest.json file is the necessary change to fix my tests because if I make the same change in my main tsconfig.json file my tests run fine.
I've also tried putting to desired tsconfig compiler options directly into the jest.config.ts file, but that doesn't seem to work either:
module.exports = {
setupFilesAfterEnv: [`./jest.setup.ts`],
testEnvironment: `jsdom`,
roots: [
`<rootDir>/test`
],
testMatch: [
`**/__tests__/**/*.+(ts|tsx|js)`,
`**/?(*.)+(spec|test).+(ts|tsx|js)`
],
transform: {
"^.+\\.(ts|tsx)$": `ts-jest`
},
globals: {
"ts-jest": {
tsConfig: {
jsx: `react`
}
}
}
}
Updated answer for jest#29 (released August 2022) and ts-jest#29 (released September 2022)
All of my React component *.tsx-related tests were broken after upgrading Jest-and-friends to version 29. I also received error messages that jestConfig.globals['ts-jest'] is now deprecated.
As per the ts-jest "Options" doc you need to use the lowercased tsconfig and not the camel-cased tsConfig.
As per the ts-jest "TypeScript Config option" doc you should modify your Jest config to jestConfig.transform['regex_match_files'].
The relevant parts of my project's configuration are below. (Caveat: note that I'm using a custom location for my config files, i.e. a dedicated ./config/ directory in the project root, but the principle of specifying the relative-path-to-config-file remains the same).
// ./package.json
// (trimmed to just the relevant parts)
"scripts": {
"test": "jest --config=./config/.jestrc.js --rootDir=./src/"
},
"devDependencies": {
"#types/jest": "^29.0.1",
"jest": "^29.0.3",
"jest-environment-jsdom": "^29.0.3",
"ts-jest": "^29.0.0",
"typescript": "^4.8.3"
}
// ./config/.jestrc.js
// (trimmed to just the relevant parts)
transform: {
'^.+\\.tsx?$': [
'ts-jest',
// required due to custom location of tsconfig.json configuration file
// https://kulshekhar.github.io/ts-jest/docs/getting-started/options/tsconfig
{tsconfig: './config/tsconfig.json'},
],
},
the correct key is tsconfig not tsConfig.

How to resolve "Cannot use import statement outside a module" in jest

I have a React application (not using Create React App) built using TypeScript, Jest, Webpack, and Babel. When trying to run yarn jest, I get the following error:
I have tried removing all packages and re-adding them. It does not resolve this. I have looked at similar questions and documentation and I am still misunderstanding something. I went so far as to follow another guide for setting up this environment from scratch and still received this issue with my code.
Dependencies include...
"dependencies": {
"#babel/plugin-transform-runtime": "^7.6.2",
"#babel/polyfill": "^7.6.0",
"babel-jest": "^24.9.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-test-renderer": "^16.11.0",
"source-map-loader": "^0.2.4"
},
"devDependencies": {
"#babel/core": "^7.6.0",
"#babel/preset-env": "^7.6.0",
"#babel/preset-react": "^7.0.0",
"#types/enzyme": "^3.9.2",
"#types/enzyme-adapter-react-16": "^1.0.5",
"#types/jest": "^24.0.13",
The component's import lines...
import * as React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import HomePage from "./components/pages";
import {
Footer,
Header,
Navigation,
} from "./components/shared";
The test file....
import * as React from "react";
import * as renderer from "react-test-renderer";
import App from "../App";
it("Renders the Footer correctly", () => {
const tree = renderer
.create(<App />)
.toJSON();
expect(tree).toMatchSnapshot();
});
I expected to be able to use named imports in my components without my tests blowing up. It appears to fix the issue if I only use default imports through my solution, but I would prefer to not go that route.
Also using Babel, Typescript and Jest. Had the same failure, driving me crazy for hours.
Ended up creating a new babel.config.js file specifically for the tests. Had a large .babelrc that wasn't getting picked up by jest no matter what i did to it. Main app still uses the .babelrc as this overrides babel.config.js files.
Install jest, ts-jest and babel-jest:
npm i jest ts-jest babel-jest
babel.config.js (only used by jest)
module.exports = {presets: ['#babel/preset-env']}
jest.config.js
module.exports = {
preset: 'ts-jest',
transform: {
'^.+\\.(ts|tsx)?$': 'ts-jest',
"^.+\\.(js|jsx)$": "babel-jest",
}
};
package.json
"scripts": {
"test": "jest"
Use Babel to transpile those JS Modules and you'll be able to write your tests with es6.
Install Babel/preset-env
npm i -D #babel/preset-env
Create a babel configuration file with the preset
//babel.config.js
module.exports = {presets: ['#babel/preset-env']}
I solved this by migrating the .babelrc file to babel.config.js! Shocker.
For future references,
I solved the problem by using below jest config, after reading Logan Shoemaker's answer.
module.exports = {
verbose: true,
setupFilesAfterEnv: ["<rootDir>src/setupTests.ts"],
moduleFileExtensions: ["js", "jsx", "ts", "tsx"],
moduleDirectories: ["node_modules", "src"],
moduleNameMapper: {
"\\.(css|less|scss)$": "identity-obj-proxy"
},
transform: {
'^.+\\.(ts|tsx)?$': 'ts-jest',
"^.+\\.(js|jsx)$": "babel-jest",
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/file.js",
}
};
try this thing if you are using babel 6
Adding #babel/plugin-transform-modules-commonjs in the plugin section of babel.config.js
or
For my case import issue was due to the react file drop by adding that to transformIgnorePatterns
"transformIgnorePatterns": ["/node_modules/(?!react-file-drop)"]
I fixed it by simply appending the pattern after the run statement in package.json runner
{
"scripts": {
...
"test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!my-library-dir)/'"
...
Then, just run npm test
Solution: my named imports were coming from index.js files and I believe ts-jest needed them as index.ts files (I'm using Typescript). If anyone else runs into this error, couldn't hurt to check if you derped your file extensions.
I wasted a lot of time on this, unfortunately, but I learned a lot about webpack configurations and Babel.
Add your test script in package.json with Node experimental feature: --experimental-vm-modules
In this way you won't require babel or other dependencies.
Examples:
"test": "NODE_OPTIONS='--experimental-vm-modules --experimental-specifier-resolution=node' jest"
If you get this error: zsh: command not found: jest, try with node passing jest.js like this:
"test": "NODE_OPTIONS='--experimental-vm-modules --experimental-specifier-resolution=node --trace-warnings' node node_modules/jest/bin/jest.js --detectOpenHandles"
I'm surprised that none of the answers does not give an elegant solution:
jest.config.js
module.exports = {
...,
globals: {
"ts-jest": {
isolatedModules: true,
},
},
};
This compiles each file separately therefore avoiding the no exports issue.
Create .babelrc on the main directory and add this code and install these packages
#babel/core, #babel/preset-env and #babel/preset-react
{
"presets": [
[
"#babel/preset-env",
{
"modules": "commonjs"
}
],
"#babel/preset-react"
]
}
Matching file extensions:
I importing a file named Todo.jsx in the root as ./src/Todo/. Whenever I changed it to Todo.js the problem went away.
Disclaimer: I'm not sure what the requirement is for having your file extension as jsx vs js for your components. It did not effect me at all, but I could imagine it could mess with intellisense or snippets.
For me renaming file to babel.config.js worked.
Here is my config file an NX project using next with Typescript along with Twin-macro
// .babelrc.js >> babel.config.js
module.exports = {
presets: [
[
"#nrwl/react/babel",
{
"runtime": "automatic",
"targets": {
"browsers": [">0.25%", "not dead"]
},
"preset-react": {
runtime: "automatic",
importSource: "#emotion/react",
},
}
],
'#babel/preset-env',
'#emotion/babel-preset-css-prop',
'#babel/preset-typescript'
],
plugins: ['#emotion', 'macros', '#babel/plugin-transform-runtime', 'react-docgen'],
}
Also, please note even updating package.json works,
https://kulshekhar.github.io/ts-jest/docs/getting-started/presets/#basic-usage
// package.json
"jest": {
// Replace `ts-jest` with the preset you want to use
// from the above list
"preset": "ts-jest"
}
I encountered the same problem with Typescript, Jest, and VueJS/VueCli 3. The normal build has no problem. only happens for Jest. I struggled for hours by searching. But no answer actually works. In my case, I have a dependency on my own typescript package which I specific "target": "es6" in the tsconfig.json. That's the root cause. So the solution is simply to change the dependent's (Not the same project) back to es5 tsconfig.json:
{
"compilerOptions": {
"target": "es5",
...
},
...
}
Personnaly I followed #ajwl setup but discovered that jsdom-worker inside setupFiles: section of jest.config.js was triggering that same error. Once removed, my tests were passing.
P.S. my babel.config.js is a bit different, since I have a Vuejs (v2) SPA (bundled with Vitejs):
module.exports = {
plugins: ['#babel/plugin-transform-modules-commonjs'],
presets: [['#babel/preset-env', { targets: { node: 'current' } }]]
}
The problem is likely that jest doesn't support esmodules natively. Which can cause problems if youre typescript target is es6 or greater.
If you are testing the built typescript output, you could simply add a module=commonjs flag while transpiling. That way, your code can run with es6 or greater and still work with Jest.
"scripts": {
"test": tsc --module commonjs && jest {your-output-folder}/
}
What's great about this is that I didn't have to add any additional babel dependencies or special jest runners :)
I solved it by changing my tsconfig.json to a compatible native output
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
It is not ideal in every scenario but you might be okay with this.
All I had to do, was simply updating the package #babel/preset-env in the dev dependencies to the latest version
// package.json
"#babel/preset-env": "^7.18.6"
None of the answers helped me, what did help me was making sure my NODE_ENV was set to test, since babel config is per NODE_ENV using the wrong NODE_ENV by accident that is not configured in babel config will mean you wont be using babel and the typescript files will not be transformed.
It took me couple of hours to figure this one out so i hope it will save someone else the time it took me.
Don't know why and how but how I solved the problem was really interesting.
Just add __mocks__ folder in your src folder and create an empty file inside __mocks__ named axios.js
I discovered that this error might be triggered when you try to load a dependency that is made for the browser and, thus, cannot work with jest (node).
I had a lot of trouble solving this issue for #zip.js/zip.js lib. But I could do it like that:
Here is my jest.config.js. Adapt it to your need. The trick here is the moduleNameMapper that will make all imports to zip.js point to the file __mocks__/#zip.js/zip.js I created in my root folder.
export default {
preset: 'ts-jest',
testEnvironment: 'node',
moduleNameMapper: {
'#zip.js/zip.js': '<rootDir>/__mocks__/#zip.js/zip.js',
},
}
And here is what I have in <rootDir>/__mocks__/#zip.js/zip.js file:
module.exports = {}
Too late for this answer :)
After trying all the possible solutions, this worked for me:
The solution, that works for me:
create a file named jest/mocks/#react-native-firebase/crashlytics.js
export default () => ({ log: jest.fn(), recordError: jest.fn(), });
create a file named jest/jestSetupFile.js
import mockFirebaseCrashlytics from './mocks/#react-native-firebase/crashlytics';
jest.mock('#react-native-firebase/crashlytics', () => mockFirebaseCrashlytics);
in package.json add
"jest": { "setupFiles": ["./jest/jestSetupFile.js"] },
I needed to do a couple things to get this to work for me
Rename my .babelrc to babel.config.js and make a little change:
// .babelrc
{
"presets": [
[
"#babel/preset-env",
{
"corejs": "3.26",
"useBuiltIns": "usage"
}
],
"#babel/preset-react"
],
...
}
// babel.config.js - This still works fine with webpack
module.exports = {
"presets": [
[
"#babel/preset-env",
{
"corejs": "3.26",
"useBuiltIns": "usage"
}
],
"#babel/preset-react"
],
...
}
Add the following to my jest config file:
{
...
"transformIgnorePatterns": [
"node_modules/(?!(react-leaflet-custom-control)/)"
],
...
}
Where react-leaflet-custom-control was the package causing issues for me.
If you're using TypeScript, and you have a tsconfig.json file, try removing "module": "esnext" if you're using it
Running npm ci fixed this problem for me.

loading local modules in JEST with JSPM

I'm trying to use jest in my JSPM project.
My jspm.config file looks like this:
SystemJS.config({
paths: {
"npm:": "jspm_packages/npm/",
"github:": "jspm_packages/github/",
"moment": "scripts/vendor/moment/moment.min.js"
}
});
In my package.json i have the follow JEST configurations:
"jest": {
"verbose": true,
"collectCoverage": true,
"moduleNameMapper": {
"^npm:(.*)": "<rootDir>/jspm_packages/npm/$1",
"^github:(.*)": "<rootDir>/jspm_packages/github/$1",
"moment": "<rootDir>/public/scripts/vendor/moment"
},
"moduleDirectories": [
"jspm_packages/npm",
"jspm_packages/github",
"public/scripts/vendor",
"node_modules"
],
"rootDir": "",
"modulePathIgnorePatterns": [
"jspm_packages/npm/js-tokens#1.0.3/"
]
},
I try the aproach of the poeticGeek answer in jest testing with es6 + jspm + systemjs + reactJS
but in my test.js whenever i import moment from 'moment'; the tests never completes, seems to enter in an infinite loop.
If i remove the moment inside the moduleNameMapper appears the following error: Cannot find module 'moment' from 'date.test.js'
Any ideas?
The problem was:"rootDir": "" in the configuration file.

WARNING: Tried to load angular more than once. - GRUNT

My pipeline looks like this:
// Client-side javascript files to inject in order
// (uses Grunt-style wildcard/glob/splat expressions)
var jsFilesToInject = [
// Dependencies like sails.io.js, jQuery, or Angular
'js/dependencies/sails.io.js',
'js/bower_components/angular/*.js',
'js/bower_components/**/*.js',
// All of the rest of your client-side js files
// will be injected here in no particular order.
'js/modules/app.js',
'js/modules/auth/services/accessLevels.js',
'js/**/*.js'
];
and my bower.json:
{
"name": "myapp",
"version": "0.0.1",
"dependencies": {
"angular": "1.3.7",
"angular-cookies": "1.3.7",
"angular-ui-router": "0.2.15"
},
"resolutions": {
"angular": "1.3.7"
}
}
I think this issue is because it's injecting angular.js and angular.min.js, any way to solve this with grunt?

Why is my gulp task not converted jsx when using reactify transform with browserify and glob

I have been working on converting a grunt task to gulp. The grunt file looks like this:
browserify: {
options: {
transform: [ require('grunt-react').browserify ]
},
client: {
src: ['react/**/*.jsx'],
dest: 'public/js/browserify/bundle.js'
}
}
I saw many examples of browserify and gulp but all of them had just a single file start point. To get round this I tried using glob. After several false starts I came up with the following. It runs without error and creates a single bundle.js file, but reactify doesn't seem to be working correctly, as jsx does not seem to be converted so I end up with the error:
Uncaught Error: Cannot find module './components/NoteApp.jsx'
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var glob = require('glob');
var reactify = require('reactify');
gulp.task('browserify', function (cb) {
glob('./react/**/*.jsx', {}, function (err, files) {
var b = browserify();
files.forEach(function (file) {
b.add(file);
});
b.transform(reactify);
b.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest('./public/js/browserify/'));
cb();
});
});
ddprrt requested some further details on structure so here is how the react folder is laid out. The code is taken from this article which uses this github zip source to demonstrate react and reflux. The project was very close to what I needed as a start point but uses Grunt instead of Gulp.
The react folder is structured like this:
react \ App.jsx
\ Bootstrap.jsx
\ components \ NoteApp.jsx
\ NoteCreationBox.jsx
\ Note.jsx
\ NoteListBox.jsx
\ NoteList.jsx
\ TextArea.jsx
The error is coming from a line in the App.jsx file:
var React = require('react');
var NoteApp=require('./components/NoteApp.jsx');
but changing this line causes the gulp talk to fail with a missing file error.
I guess I got the answer now. It was really some version mixup, reactify seems to be more advanced and handle things differently than the reactify in the original did. Might be because both are still in experimental state. I also guess that React/Reflux moved on, so you ended up with some versions which didn't quite comply. However, you still can fix it and run you app:
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var glob = require('glob');
var reactify = require('grunt-react').browserify;
gulp.task('browserify', function (cb) {
glob('./react/Bootstrap.jsx', function (err, files) {
var b = browserify({
entries: files
}).transform(reactify)
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest('./public/js/browserify/'));
cb();
});
});
Instead of using require('reactify'), we take the reactify provided by grunt-react. See the code above. You should just be able to switch the middleware. Also, don't go over all the files, just your main entry point, which is in that case Bootstrap.jsx.
I know that this is rather inconvenient, maybe when you try your own app, start with a fresh setup.
** Update**
that was my package.json afterwards, just working into the previous project:
{
"name": "react-note-app",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www",
"main": "./bin/www"
},
"engines": {
"node": ">= 0.10.0"
},
"dependencies": {
"body-parser": "~1.8.1",
"cookie-parser": "~1.3.3",
"debug": "~2.0.0",
"ejs": "~0.8.5",
"express": "~4.9.0",
"express-session": "^1.8.2",
"morgan": "~1.3.0",
"node-jsx": "^0.11.0",
"react": "^0.11.2",
"reflux": "^0.1.13",
"serve-favicon": "~2.1.3"
},
"devDependencies": {
"browserify": "^9.0.7",
"glob": "^5.0.3",
"grunt": "^0.4.5",
"grunt-browserify": "^3.0.1",
"grunt-contrib-watch": "^0.6.1",
"grunt-nodemon": "^0.3.0",
"grunt-react": "^0.9.0",
"gulp": "^3.8.11",
"react-tools": "^0.11.2",
"reactify": "^1.1.0",
"vinyl-source-stream": "^1.1.0"
}
}

Resources