squidfunk / karma-viewport

A Karma plugin for testing responsive features and layout

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Getting the TypeScript typings to work

ctwoolsey opened this issue · comments

I'm probably overlooking something simple, but I'm following the documentation as far as I can tell and I'm getting a "Cannot find name 'viewport'" error.

I added "viewport" to my frameworks as stated. Do I need to import "Viewport" in my test?
Or is this an issue with typescripting? I wasn't sure where or what to do with the line from documentation that stated: ///

I also ran across this on the web and wasn't sure if this should be installed: @types/karma-viewport

I'm using Angular-cli and just installed karma-viewport 1.0.2

This utility looks like it will be super useful in testing my responsive code.

"@angular/cli": "1.7.4",
"@angular/compiler-cli": "5.2.0",
"@angular/language-service": "5.2.0",
"@types/jasmine": "2.8.3",
"@types/jasminewd2": "2.0.2",
"@types/node": "6.0.60",
"codelyzer": "4.0.1",
"jasmine-core": "2.8.0",
"jasmine-spec-reporter": "4.2.1",
"karma": "2.0.0",
"karma-chrome-launcher": "2.2.0",
"karma-coverage-istanbul-reporter": "1.2.1",
"karma-jasmine": "1.1.0",
"karma-jasmine-html-reporter": "0.2.2",
"protractor": "5.1.2",
"ts-node": "4.1.0",
"tslint": "5.9.1",
"typescript": "2.5.3"

The easiest way is to add the following line to the file where you reference the viewport variable:

/// <reference types="karma-viewport" />

It should be enough to add this at the top of your karma.conf.js (or .ts) file, for which you would also have types available.

If I copy into karma.conf.js, I get errors of "expecting newline" after reference and "expression expected" by the '/>'

Here is my karma.conf.js file. I tried putting the above statement in via a 'types' config variable:

module.exports
= function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular/cli', 'viewport'], <-added here per documentation
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular/cli/plugins/karma'),
require('karma-viewport') <- not sure if I should have added this
],
types: ['karma-viewport'], <- this is what I've added
client:{
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true
},
angularCli: {
environment: 'dev'
},
viewport: {
breakpoints: [
{
name: "mobile",
size: {
width: 320,
height: 480
}
},
{
name: "tablet",
size: {
width: 768,
height: 1024
}
},
{
name: "screen",
size: {
width: 1440,
height: 900
}
}
]
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};

Then in the spec file I try using "viewport" like so:

it('should have mobileNavMenu link to correct urls', () => {
    viewport.set('mobile');
    const linkDes = fixture.debugElement.queryAll(By.css('#mobileMenuButtons button'));
    const links = linkDes.map(del => del.injector.get(RouterLinkStubDirective) as RouterLinkStubDirective);

    expect( linkDes.length).toBe(6);
...

But this is the error I get:

error TS2304: Cannot find name 'viewport'.

Ah sorry, for this to work your karma configuration must be written in TypeScript. Have you tried including the reference in the file where you use the viewport variable?

Yes, I've tried including it in header.component.spec.ts. But I'm not sure why it would work in a typescript file when the notation is more html format.

Copy the line exactly as it is with three leading slashes and it should work.

I have added it to karma.config.ts as follows below. Do I need to import it somehow in my spec file? I am still getting

error TS2304: Cannot find name 'viewport'.

///
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular/cli', 'viewport'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular/cli/plugins/karma'),
require('karma-viewport')
],
client: {
clearContext: false // leave Jasmine

You did not include /// <reference types="karma-viewport" /> - please try that, as I wrote before.

I have the same issue as well. When I did the three slashes reference to my .spec.ts file (at the very top), I got the error: error TS2671: Cannot augment module 'karma' because it resolves to a non-module entity.

To fix it, what I did was declare var viewport: any; in my spec file and removed the ///reference.

Also you can try it in the spec file

placing /// in the spec file didn't solve anything. However, adding "declare var viewport: any;" did get rid of the error.

Thank you

I'm going to look into this when I find some time, maybe the docs need some clarification. Reopening.

The documentation is incomplete (and also this discussion).
However this issue helped me to get your really nice and helpful plugin to work.

For our project based on angular/cli the following worked:

  1. in karma.conf.js you need to add 'viewport' in frameworks and 'require('karma-viewport')' in plugins
  2. in tsconfig.spec.json you need to add 'karma-viewport' in types

Again in code but a little bit different:

karma.conf.js

config.set({
    ...
    frameworks: [
        ... 
        'viewport'
    ],
    plugins: [
        ...
        require('karma-viewport')
    ],
   ...
});

tsconfig.spec.js

{
    ...
    "compilerOptions": {
        ...
        "types": [
            ...
            "karma-viewport"
        ]
    }
    ...
}

So the only change you made was referencing it in the types option of tsconfig.json? Don't you have to enumerate all types if you specify the types option, including those in the @types namespace? Or is it sufficient to only add karma-viewport to types?

I only posted what I added to the configuration that is already there and/or the configuration a ng new <project> would create. This is why I have ... in the snippets.
(again: I use karma-viewport in an angular/cli based project)

Here the full content of the files in action:

src/tsconfig.spec.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/spec",
    "types": [
      "karma-viewport",
      "jasmine",
      "node"
    ]
  },
  "files": [
    "test.ts",
    "polyfills.ts"
  ],
  "include": [
    "**/*.spec.ts",
    "**/*.d.ts"
  ]
}

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}

I guess you relate to node_modules/@types in typeRoots.

Could you guys having problems with the typings try the latest version (1.0.4) again? Does it work now? At some point the typings were not correctly generated anymore (my mistake, so stupid) so they were'nt included in the package, but this is fixed with the latest release.

I just installed @types/karma-viewport and everything just works fine, even without adding the ///reference.

The problem with that is that the current typings on DefinitelyTyped are not correct and incomplete.

Closing this issue, as I'm considering it fixed. To recap: the easiest way is to use the reference tag as described in the README.md somewhere in your project. It will add viewport to the global namespace.

Typedefs didn't work for me either, but this silenced the errors for me in my test file

import { Viewport } from 'karma-viewport/dist/adapter/viewport';
declare const viewport: Viewport;

The documentation is incomplete (and also this discussion).
However this issue helped me to get your really nice and helpful plugin to work.

For our project based on angular/cli the following worked:

  1. in karma.conf.js you need to add 'viewport' in frameworks and 'require('karma-viewport')' in plugins
  2. in tsconfig.spec.json you need to add 'karma-viewport' in types

Again in code but a little bit different:

karma.conf.js

config.set({
    ...
    frameworks: [
        ... 
        'viewport'
    ],
    plugins: [
        ...
        require('karma-viewport')
    ],
   ...
});

tsconfig.spec.js

{
    ...
    "compilerOptions": {
        ...
        "types": [
            ...
            "karma-viewport"
        ]
    }
    ...
}

Consider putting this into the readme - worked properly with typescript and angular.

@maperz the problem is if you put something into the types option of your tsconfig.json it will disable automatic inclusion of @types packages. I have absolutely no trouble getting this to work on my behalf following the steps outlined in the README. A repository which reproduces the error for you might be a good starting point.

If the problem is that you actually have overridden types in tsconfig.json you should know what you're doing and don't wonder why the typings aren't working. They're not working because you disabled automatic typings resolution which is a TypeScript feature (or problem, as you want) and has nothing to do with this plugin in particular. Furthermore the docs actually state that you might need to add the typings explicitly in tsconfig.json:

karma-viewport is written in TypeScript and comes with its own typings. Don't include the package using an import statement, but instead include its types via tsconfig.json or a reference within karma.conf.ts or tests: ...

The same is also true for the necessity of the require("karma-viewport") in the karma configuration. It's not necessary if you adhere to the default configuration of karma which will automatically resolve stuff from node_modules.

Thank you for the outline. Indeed, I was not aware of this automatic exclusion.

@squidfunk the default configuration does not work for vanilla Angular CLI setup, so it might be reasonable to include an extra README section - there's clearly a demand, as you can see by this thread. @gestj and @chrismbarr solutions were very helpful in my case.

I needed to also add the following to my tsconfig.json:

"typeRoots": [
      ...
      "node_modules/karma-viewport",
      ...
],
ezoic increase your site revenue