Angular 2 Unit Tests: Cannot find name 'describe' - unit-testing

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

Related

Server-side AssemblyScript: How to read a file?

I'd like to write some server-side AssemblyScript that uses the WASI interface to read a file and process the contents.
I know that AssemblyScript and the ByteCode Alliance have recently had a falling out over the "openness" of the WASI standard, but I was hoping that they would still play nicely together...
I've found several AssemblyScript tools/libraries that appear to bridge this gap, and the one that seems the simplest to use is as-wasi. After following the installation instructions, I'm just trying to run the little demo app.
All the VSCode design time errors have disappeared, but the AssemblyScript compiler still barfs at the initial import statement.
import "wasi"
import { Console, Environ } from "as-wasi/assembly";
// Create an environ instance
let env = new Environ();
// Get the HOME Environment variable
let home = env.get("HOME")!;
// Log the HOME string to stdout
Console.log(home);
Running npm run asbuild gives.
$ npm run asbuild
> file_reader#1.0.0 asbuild
> npm run asbuild:debug && npm run asbuild:release
> file_reader#1.0.0 asbuild:debug
> asc assembly/index.ts --target debug
ERROR TS6054: File '~lib/wasi.ts' not found.
:
1 │ import "wasi"
│ ~~~~~~
└─ in assembly/index.ts(1,8)
FAILURE 1 parse error(s)
The file ~lib/wasi.ts does not exist and creating this file as a softlink pointing to the index.ts in the ./node_modules/as-wasi/assembly/ directory makes no difference.
Since the library is called as-wasi and not wasi, I've tried importing as-wasi, but this also fails.
I've also tried adapting tsconfig.json to include
{
"extends": "assemblyscript/std/assembly.json",
"include": [
"../node_modules/as-wasi/assembly/*.ts",
"./**/*.ts"
]
}
But this also has no effect.
What is causing asc to think that the required library should be in the directory called ~lib/ and how should I point it to the correct place?
Thanks
Your question threw me in a bit of a rabbit hole, but I think I solved it.
So, apparently, after the wasi schism, AssemblyScript added the wasi-shim repository, that you have to install as well:
npm install --save wasi-shim
The import "wasi" is no longer necessary after version 0.20 of AssemblyScript according to the same page, so you have to remove that import entirely. Also, be sure to add the extends to your asconfig.json, as recommended in the same wasi-shim page. Mine looks like this:
{
"extends": "./node_modules/#assemblyscript/wasi-shim/asconfig.json",
"targets": {
"debug": {
"outFile": "build/debug.wasm",
"textFile": "build/debug.wat",
"sourceMap": true,
"debug": true
},
"release": {
"outFile": "build/release.wasm",
"textFile": "build/release.wat",
"sourceMap": true,
"optimizeLevel": 3,
"shrinkLevel": 0,
"converge": false,
"noAssert": false
}
},
"options": {
"bindings": "esm"
}
}
It is just the generated original asconfig.json plus that extends.
Now the things got interesting. I got a compilation error:
ERROR TS2300: Duplicate identifier 'wasi_abort'.
:
1100 │ export function wasi_abort(
│ ~~~~~~~~~~
└─ in ~lib/as-wasi/assembly/as-wasi.ts(1100,17)
:
19 │ export function wasi_abort(
│ ~~~~~~~~~~
└─ in ~lib/wasi_internal.ts(19,17)
So I investigated, and it seems that as-wasi was exporting a symbol that was the same as a symbol exported by wasi_shim. No biggie, I went into node_modules/as-wasi/, and I renamed that function into as_wasi_abort. I did this also with the invokations of the function, namely three instances found in the package.json from as-wasi:
{
"asbuild:untouched": "asc assembly/index.ts -b build/untouched.wasm -t build/untouched.wat --use abort=as_wasi_abort --debug",
"asbuild:small": "asc assembly/index.ts -b build/optimized.wasm -t build/optimized.wat --use abort=as_wasi_abort -O3z ",
"asbuild:optimized": "asc assembly/index.ts -b build/optimized.wasm -t build/optimized.wat --use abort=as_wasi_abort -O3",
}
Having done all this, the package compiled and the example from Wasm By Example finally worked.
Your code should compile now, and I will try to make a pull request to all the places necessary so that the examples are updated, the code in as-wasi is updated, and so that nobody has to go through this again. Please comment if there are further problems.
Edit: It seems that I was right about the wasi_abort function being a problem. It is actually removed on the as-wasi repo, but the npm package is outdated. I asked in my pull request for it to be updated.

enabling pylint_django plugin in vscode, pylint stop working

That's my user settings in vscode
{
"python.pythonPath": "/Users/cristiano/miniconda3/envs/django-rest-2/bin/python",
"python.linting.pylintEnabled": true,
"python.linting.enabled": true,
"python.linting.pylintArgs": [
"--load-plugins",
"pylint_django"
],
}
I installed the plugin via conda, same as the pylint
pylint 2.1.1 py36_0
pylint-django 0.11.1 py_1 conda-forge
pylint-plugin-utils 0.4 py_0 conda-forge
If i commented out the "python.linting.pylintArgs" section, pylint works with no problem. I ned to enable the plugin to avoid django-specific errros such as "Entity.objects.all()", but if I enable it, the lint stop working: it does not highlight standard errors o warning the previously was doing it.
I have same exact behaviour using vscode for win and mac. I tried also to use the .pylintrc file as described here but I have the same result: lint stop working.
Same behaviour using base conda env or a custom one.
This config for pylint is working for me:
"python.linting.pylintEnabled": true,
"python.linting.pylintArgs": [
"--disable=C0111", // missing docstring
"--load-plugins=pylint_django,pylint_celery",
],
I just got the same issue. Like #J0hnG4lt said, I had a problem with the python path. I didn't point to the path of the environment, which I have installed pylint_django. This config is work for me. Thanks #Manu.
"python.pythonPath": "/Users/mc976/Documents/Programming/Python/Practice/music_service/venv/bin/python3",
"python.linting.pylintEnabled": true,
"python.linting.pylintArgs": [
"--disable=C0111",
"--load-plugins",
"pylint_django"
]
Besides, I think you should check your environment to make sure that you have correctly installed pylint_django by using pip list.
My issue was more prosaic (but perhaps it will help other forehead slappers like myself). Run the PIP install in the correct virtualenv directory!
pip install pylint-django --upgrade
Also note that plugin errors cause Pylint to completely fail to load silently. Start with blank pylintArgs and slowly add them back one at a time to see where things go awry.
found a working answer for myself here: https://donjayamanne.github.io/pythonVSCodeDocs/docs/linting/
my settings.json file now reads:
{
"python.pythonPath": "C:\\ProgramData\\Anaconda3\\envs\\djangoSite2\\python.exe",
"python.linting.pylintEnabled": true,
"python.linting.pylintArgs": ["--disable=C0111","--load-plugins", "pylint_django"],
}
this then adds linting, but doesn't throw an error on fields that it can't find (like the Entity.objects.all() one), but has the disadvantage that if you then try and reference something that really doesn't exist it doesn't throw an error.
It now works on my Mac. This is my workspace's settings.json:
{
"python.linting.pylintEnabled": true,
"python.linting.pycodestyleEnabled": false,
"files.autoSave": "afterDelay",
"editor.fontSize": 14,
"editor.wordWrapColumn": 90,
"editor.autoClosingQuotes": "beforeWhitespace",
"python.pythonPath": "/Users/myname/anaconda3/envs/myproject/bin/python",
"python.linting.pylintArgs": [
"--disable=C0111", // missing docstring
"--load-plugins=pylint_django",
],
}
I had to be careful to have installed pylint-django into the correct python environment. For me, this meant running this command in the terminal:
$ /Users/myname/anaconda3/envs/myproject/bin/python -m install pip pylint pylint-django
python.pythonPath is deprecated. You should use python.defaultInterpreterPath instead
I ran into an error related to pylint not being able to parse JSON correctly. All I had to do was add an 's' to my config to make it plugins (plural) instead of plugin. Then everything started working.
"python.linting.pylintArgs": [
"--load-plugins=pylint_django",
],

Vue-test-utils | Jest: How to handle dependencies?

THE SITUATION:
I am implementing unit-testing in my Vue app, using vue-test-utils with Jest configuration.
When I am testing simple components everything is fine. But when I am testing components that import other dependencies, the test fails.
CONFIGURATION:
Vue version: 2.5.17
#vue/test-utils: 1.0.0-beta.20
cli-plugin-unit-jest: 3.0.3
babel-jest: 23.0.1
THE ERROR MESSAGE:
The exact error message depends on which dependency I am importing.
For example with epic-spinners the error is:
SyntaxError: Unexpected token import
With vue-radial-progress the error is:
SyntaxError: Unexpected token <
HOW TO REPRODUCE:
Make a fresh install of vue (with Jest as unit testing suite)
Run the example test, it should pass
Install a dependency (for example: npm install --save epic-spinners)
Import the dependency inside the HelloWorld component
Run the test again (without changing anything)
If I do these steps, the test fails with the above error message.
THE QUESTION:
How can I handle dependencies import in vue-test-utils / Jest ?
The problem was that some modules may not be compiled correctly.
The solution is to use the transformIgnorePatterns property of the Jest settings. That is, from the docs:
An array of regexp pattern strings that are matched against all source
file paths before transformation. If the test path matches any of the
patterns, it will not be transformed.
In my case, this is how I have solved the issue:
transformIgnorePatterns: [
"node_modules/(?!epic-spinners|vue-radial-progress)"
],
EDIT:
This is my jest.config.js
module.exports = {
moduleFileExtensions: [
'js',
'jsx',
'json',
'vue'
],
transform: {
'^.+\\.vue$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
'^.+\\.jsx?$': 'babel-jest',
},
transformIgnorePatterns: [
"node_modules/(?!epic-spinners|vue-radial-progress)"
// "node_modules/(?!epic-spinners)",
],
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1'
},
snapshotSerializers: [
'jest-serializer-vue'
],
testMatch: [
'**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
],
testURL: 'http://localhost/'
}
In addition to #FrancescoMussi's answer, after editing my jest.config.js, in case you get the error: jest-transform-stub not found, just install it. in my case I didn't had installed jest-transform-stub and jest-serializer-vue. after installing those my tests started working.
npm install --save-dev jest-serializer-vue
https://www.npmjs.com/package/jest-serializer-vue
and
npm install --save-dev jest-transform-stub
https://www.npmjs.com/package/jest-transform-stub
In addition to #FrancescoMussi's solution, if it is still not working for you, make sure your Babel config is in the correct place as per the Jest docs
I had moved my Babel config to package.json which Babel wasn't detecting due to Vue CLI installing Babel 7. Moving Babel config back to babel.config.js resolved the issue for me.

Change Ember build directory (dist folder) without command line flags

I am trying to make my Ember project build to a directory outside of the project and for future builds I don't want to use command line flags each time.
ember build --output-path=/not-dist will work for me but I want Ember to add the flag automatically.
outputPaths: {
app: {
html: '../presentation/index.cfm',
css: {
'app': '../presentation/assets/ember-presentation-viewer.css'
},
js: '../presentation/assets/ember-presentation-viewer.js'
},
vendor: {
css: '../presentation/assets/vendor.css',
js: '../presentation/assets/vendor.js'
}
}
I have tried this as per the ember-cli documentation but ember-presentation-viewer.css was insisting on getting built in the dist directory with all the additional paths put there.
Is there a way to do this?
Go to package.json. Change scripts/build command:
"scripts": {
"build": "ember build --output-path=/not-dist"
},
From now on, run:
npm run build
You can configure your .ember-cli.js file to specify flags that should always be included in your command line builds (in lower camel case), as per this page in the Ember docs. To change the output directory you'll want to add the following line: "outputPath": "../../example-folder/presentation".
So your final .ember-cli.js should look like this:
{
/*
Ember CLI sends analytics information by default. The data is completely
anonymous, but there are times when you might want to disable this behavior.
Setting `disableAnalytics` to true will prevent any data from being sent.
*/
"disableAnalytics": false,
"outputPath": "../../example-folder/presentation"
}

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.