Angular 4 Unit Test cannot find name alert, confirm, event - unit-testing

Running ng test in angular-cli with Angular 4.0.0 gives errors like:
Cannot find name 'alert'
Cannot find name 'confirm'
Cannot find name 'Event'
This wasn't happening with Angular 2. Looks like something is missing here but what is it?
ng serve and build work fine.

In my case this was solved by adding "dom" to the "lib" array in tsconfig. I had a tsconfig.app.json that was used for building the app normally, and a tsconfig.spec.json that was just used for unit testing. This latter one was missing "dom".
{
"compilerOptions": {
...
"lib": [
"es2016",
"dom"
],
...
}

I was able to solve this by changing typings.d.ts according to latest cli documentation.
src/typings.d.ts:
Old:
/* SystemJS module definition */
declare var module: {
id: string;
};
New:
/* SystemJS module definition */
declare var module: NodeModule;
interface NodeModule {
id: string;
}

To fix the issue I have generated a new project using latest #angular/cli and then compared and updated all of my tsconfg files to the current format.

Related

Is there a way to reference environment variables for an npm package from a consumer app?

I am creating a package on npm and for simplicity reasons I am trying to use environment variables in my npm package ( since user secret is needed ) that would be defined by a consumer app. But I seem to run into build issues when using the created package.
The structure looks something like this:
My demo app
|
|-----My npm package
|
|-----Other packages for my demo app
...
I have my npm package ( on npm ) and a demo app to showcase how the package works. I have environment variables used in the package, but I want to define them in my demo app.
In my package I am referencing the environment variables as such:
// My package
// auth-config.js
const config = {
variable1: import.meta.env['PUBLIC_VITE_VARIABLE_1'],
variable2: import.meta.env['PUBLIC_VITE_VARIABLE_2'],
variable3: import.meta.env['PUBLIC_VITE_VARIABLE_3']
};
export default config;
And later using them in my package code:
// My package
// auth-service.ts
const user = await getUser({
variable1: config.variable1,
variable2: config.variable2,
variable3: config.variable3
});
Then I have them defined in my demo app:
// Demo app
// .env
PUBLIC_VITE_VARIABLE_1=some-value
PUBLIC_VITE_VARIABLE_2=some-value-2
PUBLIC_VITE_VARIABLE_3=some-value-3
Then, when building ( npm run build ) my demo application, I am getting the following errors:
TypeError: Cannot read properties of undefined (reading 'PUBLIC_VITE_VARIABLE_1')
at file:///C:/Users/user1/Namu/login-with-auth/node_modules/my-app/auth0/auth-config.js:2:28
However, the dev build works completely fine. And it uses the variables successfully as well.
My configuration for both the package and the demo app is:
Svelte + Svelte Kit
Vite
Typescript
I have tried using different approaches to import environment variables ( process.env instead of import.meta.env ) inside the package. I have also tried updating the svelte.config.js and vite.config.js with different paths to environment variables to try and reach the scope of the application that uses this package.
I am not sure where to go from here, since I can't find any definitive answer online and nothing seems to work so far.
I was able to solve the issue in the end. Keep in mind I am using svelte + svelte-kit + vite in both the package and the demo app using the package.
The fix goes like this:
Name the environment variables properly. Naming convention should follow what the bundler says, not what the framework says. In my case for vite it has to start with VITE_, so the environment variable would be VITE_VARIABLE_1. More info can be found Here.
Side note: this is also configurable, but I could not make the configurations work in my favour.
Using proper references in the package. For vite, the correct way to reference an env variable is by using import.meta.env['VITE_VARIABLE_1'].
Adding checks for undefined when using the variables in the package like so: import.meta.env ? import.meta.env['VITE_VARIABLE_1'] : ''.
This let's you avoid the build errors that I was running into, since at build time, import.meta.env is not defined.
And this is how the final files look like:
Where the environment variables are referenced:
// My package
// auth-config.js
const variable1 = import.meta.env ? import.meta.env['PUBLIC_VITE_VARIABLE_1'] : '';
const variable2 = import.meta.env ? import.meta.env['PUBLIC_VITE_VARIABLE_2'] : '';
const variable3 = import.meta.env ? import.meta.env['PUBLIC_VITE_VARIABLE_3'] : '';
const config = {
variable1,
variable2,
variable3
};
Where the environment variables are used:
// My package
// auth-service.ts
const user = await getUser({
variable1: config.variable1,
variable2: config.variable2,
variable3: config.variable3
});
Where the environment variables are defined:
// Demo app
// .env
PUBLIC_VITE_VARIABLE_1=some-value
PUBLIC_VITE_VARIABLE_2=some-value-2
PUBLIC_VITE_VARIABLE_3=some-value-3
You can also look at the insides of the created Package.
And the coresponding files: auth-config.js, auth-service.ts.

Looking for documentation setup jest for unit test of admin plugin

my project was created with the swdc create-project ...
Is there a documentation, a tutorial or description for the right setup/configuration unit testing with JEST for custom plugin in administration?
This tutorial describes only how to write a test
But i think there must be a official setup documentation because of versions etc.
EDIT: a tutorial with code is now avialable
Using the suggested solution and execute the test, throws an configuration error:
● Test suite failed to run
Configuration error:
Could not locate module src/core/factory/module.factory mapped as:
undefined/src$1.
Please check your configuration for these entries:
{
"moduleNameMapper": {
"/^src(.*)$/": "undefined/src$1"
},
"resolver": undefined
}
...
Cause of error:
process.env.ADMIN_PATH not setted but required in %Project%/custom/plugins/%MyPlugin%/src/Resources/app/administration/node_modules/#shopware-ag/jest-preset-sw6-admin/jest-preset.js
My solution:
set process.env.ADMIN_PATH in %Project%/custom/plugins/%MyPlugin%/src/Resources/app/administration/jest.config.js
// jest.config.js
...
const { join, resolve } = require('path');
process.env.ADMIN_PATH = resolve('../../../../../../../src/Administration/Resources/app/administration');
...
I think it is easiest to just copy and adapt from a plugin that already has jest tests set up. Look at the administration directory for SwagPayPal for example. Copy the dependency and script sections from their package.json. Also copy the entire jest.config.js. Then within the administration directory of your plugin you should be able to npm install followed by npm run unit or npm run unit-watch and it should find *.spec.js files within the test sub-directory.

Module <rootDir>/node_modules/vue-jest in the transform option was not found

I got an error and I need your help. Thank for watching this question.
My situation: I am configuring Drone CI tool for my project and I get this when I run unit test on drone.yml.
Validation Error:
Module <rootDir>/node_modules/vue-jest in the transform option was not found.
Configuration Documentation:
https://jestjs.io/docs/configuration.html
Here is my jest.conf.js
transform: {
"^.+\\.js$": "babel-jest",
".*\\.vue$": "<rootDir>/node_modules/vue-jest"
},
What I have tried:
Remove <rootDir>/node_modules/. But I got an another error Module vue-jest in the transform option was not found.. So I think it is not the right solution
npm install --save-dev vue-jest
and rerun your test
Take a note that vue-jest is currently (2022) distributed in 3 concurrent packages:
vue-jest
#vue/vue2-jest
#vue/vue3-jest
In my case I've upgraded some dependencies and I had to switch from vue-jest to #vue/vue3-jest.
So my jest.config.js has to change accordingly:
module.exports = {
...
transform: {
"^.+\\.vue$": "#vue/vue3-jest",
},
...
}

Angular 2 Unit Tests: Cannot find name 'describe'

I'm following this tutorial from angular.io
As they said, I've created hero.spec.ts file to create unit tests:
import { Hero } from './hero';
describe('Hero', () => {
it('has name', () => {
let hero: Hero = {id: 1, name: 'Super Cat'};
expect(hero.name).toEqual('Super Cat');
});
it('has id', () => {
let hero: Hero = {id: 1, name: 'Super Cat'};
expect(hero.id).toEqual(1);
});
});
Unit Tests work like a charm. The problem is: I see some errors, which are mentioned in tutorial:
Our editor and the compiler may complain that they don’t know what it
and expect are because they lack the typing files that describe
Jasmine. We can ignore those annoying complaints for now as they are
harmless.
And they indeed ignored it. Even though those errors are harmless, it doesn't look good in my output console when I receive bunch of them.
Example of what I get:
Cannot find name 'describe'.
Cannot find name 'it'.
Cannot find name 'expect'.
What can I do to fix it?
I hope you've installed -
npm install --save-dev #types/jasmine
Then put following import at the top of the hero.spec.ts file -
import 'jasmine';
It should solve the problem.
With Typescript#2.0 or later you can install types with:
npm install -D #types/jasmine
Then import the types automatically using the types option in tsconfig.json:
"types": ["jasmine"],
This solution does not require import {} from 'jasmine'; in each spec file.
npm install #types/jasmine
As mentioned in some comments the "types": ["jasmine"] is not needed anymore, all #types packages are automatically included in compilation (since v2.1 I think).
In my opinion the easiest solution is to exclude the test files in your tsconfig.json like:
"exclude": [
"node_modules",
"**/*.spec.ts"
]
This works for me.
Further information in the official tsconfig docs.
You need to install typings for jasmine. Assuming you are on a relatively recent version of typescript 2 you should be able to do:
npm install --save-dev #types/jasmine
With Typescript#2.0 or later you can install types with npm install
npm install --save-dev #types/jasmine
then import the types automatically using the typeRoots option in tsconfig.json.
"typeRoots": [
"node_modules/#types"
],
This solution does not require import {} from 'jasmine'; in each spec file.
In order for TypeScript Compiler to use all visible Type Definitions during compilation, types option should be removed completely from compilerOptions field in tsconfig.json file.
This problem arises when there exists some types entries in compilerOptions field, where at the same time jest entry is missing.
So in order to fix the problem, compilerOptions field in your tscongfig.json should either include jest in types area or get rid of types comnpletely:
{
"compilerOptions": {
"esModuleInterop": true,
"target": "es6",
"module": "commonjs",
"outDir": "dist",
"types": ["reflect-metadata", "jest"], //<-- add jest or remove completely
"moduleResolution": "node",
"sourceMap": true
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules"
]
}
Solution to this problem is connected with what #Pace has written in his answer. However, it doesn't explain everything so, if you don't mind, I'll write it by myself.
SOLUTION:
Adding this line:
///<reference path="./../../../typings/globals/jasmine/index.d.ts"/>
at the beginning of hero.spec.ts file fixes problem. Path leads to typings folder (where all typings are stored).
To install typings you need to create typings.json file in root of your project with following content:
{
"globalDependencies": {
"core-js": "registry:dt/core-js#0.0.0+20160602141332",
"jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
"node": "registry:dt/node#6.0.0+20160807145350"
}
}
And run typings install (where typings is NPM package).
In my case, the solution was to remove the typeRoots in my tsconfig.json.
As you can read in the TypeScript doc
If typeRoots is specified, only packages under typeRoots will be included.
I'm up to the latest as of today and found the best way to resolve this is to do nothing...no typeRoots no types no exclude no include all the defaults seem to be working just fine. Actually it didn't work right for me until I removed them all. I had:
"exclude": [
"node_modules"
]
but that's in the defaults so I removed that.
I had:
"types": [
"node"
]
to get past some compiler warning. But now I removed that too.
The warning that shouldn't be is:
error TS2304: Cannot find name 'AsyncIterable'.
from node_modules\#types\graphql\subscription\subscribe.d.ts
which is very obnoxious so I did this in tsconfig so that it loads it:
"compilerOptions": {
"target": "esnext",
}
since it's in the esnext set. I'm not using it directly so no worries here about compatibility just yet. Hope that doesn't burn me later.
I'll just add Answer for what works for me in "typescript": "3.2.4" I realized that jasmine in node_modules/#types there is a folder for ts3.1 under the jasmine type so here are the steps:-
Install type jasmine npm install -D #types/jasmine
Add to tsconfig.json jasmine/ts3.1
"typeRoots": [
...
"./node_modules/jasmine/ts3.1"
],
Add Jasmine to the types
"types": [
"jasmine",
"node"
],
Note: No need for this import 'jasmine'; anymore.
Only had to do the following to pick up #types in a Lerna Mono-repo
where several node_modules exist.
npm install -D #types/jasmine
Then in each tsconfig.file of each module or app
"typeRoots": [
"node_modules/#types",
"../../node_modules/#types" <-- I added this line
],
In my case, I was getting this error when I serve the app, not when testing. I didn't realise I had a different configuration setting in my tsconfig.app.json file.
I previously had this:
{
...
"include": [
"src/**/*.ts"
]
}
It was including all my .spec.ts files when serving the app. I changed the include property toexclude` and added a regex to exclude all test files like this:
{
...
"exclude": [
"**/*.spec.ts",
"**/__mocks__"
]
}
Now it works as expected.
I had this error in an angular library. Turns out I accidentally included my .spec file in the exports in my public-api.ts. Removing the export fixed my issue.
Look at the import maybe you have a cycle dependency, this was in my case the error, using import {} from 'jasmine'; will fix the errors in the console and make the code compilable but not removes the root of devil (in my case the cycle dependency).
I'm on Angular 6, Typescript 2.7, and I'm using Jest framework to unit test.
I had #types/jest installed and added on typeRoots inside tsconfig.json
But still have the display error below (i.e: on terminal there is no errors)
cannot find name describe
And adding the import :
import {} from 'jest'; // in my case or jasmine if you're using jasmine
doesn't technically do anything, so I thought, that there is an import somewhere causing this problem, then I found, that if delete the file
tsconfig.spec.json
in the src/ folder, solved the problem for me. As #types is imported before inside the rootTypes.
I recommend you to do same and delete this file, no needed config is inside. (ps: if you're in the same case as I am)
If the error is in the .specs file
app/app.component.spec.ts(7,3): error TS2304: Cannot find name 'beforeEach'.
add this to the top of your file and npm install rxjs
import { range } from 'rxjs';
import { map, filter } from 'rxjs/operators';
Just add to your tsconfig.json, and be sure that you don't have "**/*.spec.ts"
in exclude
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
My working tsconfig.json

How to use webpack import aws-sdk

I found this issues in the official, but it looks like they refused to answer.
So I can only ask questions on SO.
Here is my Error&Warning Log:
WARNING in ./~/aws-sdk/lib/util.js
Critical dependencies:
40:30-45 the request of a dependency is an expression
43:11-53 the request of a dependency is an expression
# ./~/aws-sdk/lib/util.js 40:30-45 43:11-53
WARNING in ./~/aws-sdk/lib ^\.\/.*$
Module not found: Error: Cannot resolve directory '.' in /Users/me/Documents/Sources/my-project/client/node_modules/aws-sdk/lib
# ./~/aws-sdk/lib ^\.\/.*$
WARNING in ./~/aws-sdk/lib/api_loader.js
Critical dependencies:
13:15-59 the request of a dependency is an expression
104:12-46 the request of a dependency is an expression
108:21-58 the request of a dependency is an expression
114:18-52 the request of a dependency is an expression
# ./~/aws-sdk/lib/api_loader.js 13:15-59 104:12-46 108:21-58 114:18-52
WARNING in ./~/aws-sdk/lib/region_config.json
Module parse failed: /Users/me/Documents/Sources/my-project/client/node_modules/aws-sdk/lib/region_config.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
| "rules": {
| "*/*": {
| "endpoint": "{service}.{region}.amazonaws.com"
# ./~/aws-sdk/lib ^\.\/.*$
ERROR in ./~/aws-sdk/lib/api_loader.js
Module not found: Error: Cannot resolve module 'fs' in /Users/me/Documents/Sources/my-project/client/node_modules/aws-sdk/lib
# ./~/aws-sdk/lib/api_loader.js 1:9-22
ERROR in ./~/aws-sdk/lib/services.js
Module not found: Error: Cannot resolve module 'fs' in /Users/me/Documents/Sources/my-project/client/node_modules/aws-sdk/lib
# ./~/aws-sdk/lib/services.js 1:9-22
There are three types:
Cannot resolve module 'fs'
I only need to install fs can solve this.
need an appropriate loader
Well, this will need to install json-loader, and set it in webpack.config.js, but also can solve.
Critical dependencies
Module not found: Error: Cannot resolve directory '.'
I webpack newbie.So, i don't know how to solve this.
Will someone help me? thanks.
UPDATE:
Module not found: Error: Cannot resolve directory '.'
that is my fault, config file's extensions missing a .
I found this blog post that fixed it for me.
Essentially you need to import the built version of the library.
All credit goes to the author. Here is the code:
require('aws-sdk/dist/aws-sdk');
var AWS = window.AWS;
ES6 version:
import 'aws-sdk/dist/aws-sdk';
const AWS = window.AWS;
config:
module: {
noParse: [
/aws/
]
}
usage:
window.AWS to the reference of the global AWS object.
Using the noParse method should work if you are creating a node package, as this is setting webpack to not apply any parsing/loaders. This did not work for me when creating a umd formatted output file/library.
To create a umd formatted library I had to use loaders to Browserify aws-sdk and handle json files.
Install the loaders:
npm install json-loader --save-dev
npm install transform-loader brfs --save-dev
Webpack Config:
module: {
loaders: [
{ test: /aws-sdk/, loaders: ["transform?brfs"]},
{ test: /\.json$/, loaders: ['json']},
]
},
output: {
library: 'LibraryName',
libraryTarget: 'umd'
},
resolve: {
extensions: ['', '.js']
}
Replace LibraryName with you own namespacing. Currently the library would be used through a constructor as follows:
var libObj = new LibraryName();
AWS SDK added support to webpack starting from version 2.6.1, please see Using webpack and the AWS SDK for JavaScript to Create and Bundle an Application – Part 1 blog post describing how to require aws-sdk into webpack bundle.
use npm install json-loader --save-dev
add the following code to webpack.config.js
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
exclude: /node_modules/,
},
{
test: /.json$/,
loaders: ['json']
}]
}
Just import * as AWS from 'aws-sdk'
Notice that we specified a loader to tell webpack how to handle importing JSON files, in this case by using the json-loader we installed earlier. By default, webpack only supports JavaScript, but uses loaders to add support for importing other file types as well. The AWS SDK makes heavy use of JSON files, so without this extra configuration, webpack will throw an error when generating the bundle.
Update(2015-10-20):
aws-sdk fix this. i can use it from npm.
thanks, aws-sdk team.