Code Monkey home page Code Monkey logo

karma-viewport's Introduction

Github Action Codecov Downloads npm

karma-viewport

Karma viewport resizer for testing responsive features and layout

Installation

npm install karma-viewport

Usage

Add viewport to the list of frameworks inside your Karma configuration:

// karma.conf.js
module.exports = function(config) {
  config.set({
    frameworks: ["viewport"]
  })
}

This will expose the global variable viewport to your tests, which allows setting the dimensions of the viewport, e.g.:

// Set to 320px x 100%
viewport.set(320)

// Set to 320px x 480px
viewport.set(320, 480)

// Reset to 100% x 100%
viewport.reset()

Note that you (probably) cannot use viewport in the top-level scope of your tests, as Karma might not have initialized all plugins until all files were read, so makes sure to call the respective functions from the setup hooks of your test framework or from within your tests.

Browser support

Chrome, Firefox, Safari, Edge 13-15, IE 9-11 and possibly some more.

Configuration

config.viewport.context

By default, viewport will target the default iframe#context of Karma, which is enabled through client.useIframe (see the configuration guide). This will also wrap the debug context to run inside the iframe#context.

To run tests within a custom, separate context, e.g. iframe#viewport:

// karma.conf.js
module.exports = function(config) {
  config.set({
    frameworks: ["viewport"]

    // Viewport configuration
    viewport: {
      context: "#viewport"
    }
  })
}

Note that the iframe#viewport element must be present in the context.html and debug.html files that are served by Karma. You can override the files, or add an iframe element dynamically before running the tests. Using a separate, custom context makes it possible to load entire webpages for testing:

await viewport.load("/path/to/fixture.html")

config.viewport.breakpoints

For easier, and less repetitive testing, named breakpoints can be easily set:

// karma.conf.js
module.exports = function(config) {
  config.set({
    frameworks: ["viewport"]

    // Viewport configuration
    viewport: {
      breakpoints: [
        {
          name: "mobile",
          size: {
            width: 320,
            height: 480
          }
        },
        {
          name: "tablet",
          size: {
            width: 768,
            height: 1024
          }
        },
        {
          name: "screen",
          size: {
            width: 1440,
            height: 900
          }
        }
      ]
    }
  })
}

The viewport dimensions can then be set using the names of the breakpoints:

// Set to 320px x 480px
viewport.set("mobile")

// Set to 1440px x 900px
viewport.set("screen")

// Reset to 100% x 100%
viewport.reset()

Furthermore, breakpoints can be iterated:

// Run tests for mobile, tablet and screen
viewport.each(name => {
  // ...
})

// Run tests for tablet and screen
viewport.from("tablet", name => {
  // ...
})

// Run tests for mobile and tablet
viewport.to("tablet", name => {
  // ...
})

// Run tests for tablet and screen
viewport.between("tablet", "screen", name => {
  // ...
})

After breakpoint iteration, viewport.reset() is called internally. If the callback provided to the breakpoint returns a Promise, the return value of the function will also be a Promise. This enables asynchronous tests:

viewport.each(async name => {
  // await ...
})

TypeScript

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:

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

License

MIT License

Copyright (c) 2017-2020 Martin Donath

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

karma-viewport's People

Contributors

altearius avatar dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar jr01 avatar shirblc avatar squidfunk avatar thorn0 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

karma-viewport's Issues

Debug context middleware not being registered

Description

I can't figure out how to get the debug context middleware to be automatically registered.

This line returns false for me (I think config.context as well as client are undefined in my environment):

if (config.context === "#context" && client.useIframe) {
.

I can workaround this by manually adding beforeMiddleware: ['viewport'] to my karma.conf.js.

Expected behavior

Middleware to automatically be initialized (or clear instructions on how to enable it).

Actual behavior

Middleware setup is skipped.

Steps to reproduce the bug

  1. Follow setup instructions on README.
  2. Run tests in debug context
  3. Notice the debug.html doesn't have any iframe

Package versions

  • karma-viewport: 0.4.1

System information

  • OS: Ubuntu
  • Browser: Chrome

Invalid file type warning

Description

Running Karma tests with this module enabled I get the following warning:

01 04 2019 14:36:33.724:WARN [middleware:karma]: Invalid file type, defaulting to js. json

Package versions

  • karma-viewport: 1.0.4
  • karma: 4.0.1

Is there a good way to test scrolling within the viewport?

Hello.
I just want to test scrolling behavior on different viewport sizes.
Right now i'm scrolling viewport content with viewport.el_.contentWindow.scrollTo(0,101). But then i need also to reset scrollTop after each test.
I'm just curious if there is a better approach for this.

Error with PhantomJs

Description

I'm trying to configure karma-viewport with nwb

It uses the same configuration as karma. Reference here

Expected behavior

Should be able to run tests

Actual behavior

I get this error:

13 02 2018 20:00:34.010:INFO [karma]: Karma v2.0.0 server started at http://0.0.0.0:9876/
13 02 2018 20:00:34.011:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
13 02 2018 20:00:34.032:INFO [launcher]: Starting browser PhantomJS
13 02 2018 20:00:34.260:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket _DmFXaxpo6oUgeICAAAA with id 25650588
PhantomJS 2.1.1 (Linux 0.0.0) ERROR
  {
    "message": "ReferenceError: Can't find variable: describe\nat webpack:///tests/index-test.js:12:0 <- tests/index-test.js:23099:9",
    "str": "ReferenceError: Can't find variable: describe\nat webpack:///tests/index-test.js:12:0 <- tests/index-test.js:23099:9"
  }
PhantomJS 2.1.1 (Linux 0.0.0): Executed 0 of 0 ERROR (0.134 secs / 0 secs)
Karma exit code was 1
error Command failed with exit code 1.

Steps to reproduce the bug

  1. Create package with nwb
  2. Include in nwb.config.js:
  karma: {
    frameworks: [
      'viewport'
    ],
    plugins: [
      require('karma-viewport')
    ]
  }
  1. Run npm test
  2. Observe

Package versions

   "karma-viewport": "^0.4.2",
    "nwb": "0.21.x",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",

System information

  • OS: Linux debian sid amd64
  • Browser: PhantomJS (?)

Thanks a lot!!

Source map issues

#458 doesn't look like the correct solution:

  pattern: file,
  included: true,
  served,
  watched: false

served: false means that the request to this file will lead to 404, and indeed that's what happens for me.

13 10 2020 15:25:17.700:WARN [middleware:karma]: Unable to determine file type from the file extension, defaulting to js.
  To silence the warning specify a valid type for <...>/node_modules/karma-viewport/dist/adapter/index.js.map in the configuration file.
  See http://karma-runner.github.io/latest/config/files.html
13 10 2020 15:25:18.044:WARN [web-server]: 404: /base/node_modules/karma-viewport/dist/adapter/index.js.map?666b2c333d842e2f4a6850c5c8454da4de299797
13 10 2020 15:25:18.453:WARN [web-server]: 404: /base/node_modules/karma-viewport/dist/adapter/index.js.map?666b2c333d842e2f4a6850c5c8454da4de299797

Overall, the combo included: true, served: false doesn't seem to make sense:

included - Should the files be included in the browser using <script> tag?

Why would we want to load a source map using a script tag?

served - Should the files be served by Karma's webserver?

Yes, we want this file. Why set served to false?

cc: @altearius

Getting the TypeScript typings to work

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"

Viewport is not defined in Karma DEBUG RUNNER

Description

Test runs successfully and passes when running ng test in angular 4, but when debugging the tests through karma, viewport is undefined

Expected behavior

For viewport to be defined and tests to pass in debug mode.

Actual behavior

viewport is not being defined

Steps to reproduce the bug

  1. install karma-viewport using npm to an ng4 project
  2. add karma-viewport to karma.conf requirements
  3. add 'viewport' to karma frameworks array
  4. create a test and import viewport using 'declare const viewport'
  5. run test (success)
  6. click debug in karma window
  7. once successful tests will fail.

Package versions

  • karma-viewport: ^0.1.2

System information

  • Browser: Chrome

404 for adapter sourcemap.

Description

When using Karma's debug runner, the Chrome devtools makes a request to load the adapter.js file's sourcemap, adapter\index.js.map.

The adapter\index.js.map file has not been included as one of the files that Karma is allowed to serve, so this generates a 404 error, both in the Chrome dev tools and in the Karma log.

Expected behavior

No 404 should occur and the sourcemap should load successfully.

Actual behavior

A 404 error is generated in the Chrome dev tools:

image

And in the Karma log:

image

Steps to reproduce the bug

  1. Open Karma in "Watch" mode with Chrome.
  2. In the Chrome tab, click "Debug" to open the Karma debug runner.
  3. Press F12 to open the Chrome Dev Tools. This triggers the request to the source map.
  4. Observe the 404 error.

Package versions

  • karma-viewport: 1.0.6
  • karma: 4.4.1

System information

  • OS: Windows 10
  • Chrome 83.0.4103.116

Log4js Vulnerability

Description

Looks like the current version of karma-viewport depends on a vulnerable version of log4js. It also seems that karma-viewport depends on quite a few outdated packages. I know this isn’t production dependency so it’s probably not critical, but it would be really great to have updated sub-dependencies & dependencies… Is there any chance they (or at least log4js) can be upgraded, @squidfunk?

Expected behavior

To have non-vulnerable dependencies.

Actual behavior

There’s a vulnerable version of log4js.

Steps to reproduce the bug

  1. Install karma-viewport in a project. You’ll see the npm audit alert.

Package versions

  • karma-viewport: 1.0.8
  • karma: 6.3.17

System information

  • OS: macOS / Linux 20.04
  • Browser: Chromium

ReferenceError: viewport is not defined

Description

When I'm trying to use this plugin, I end up on ReferenceError: viewport is not defined error.

Expected behavior

It runs test.

Actual behavior

It fails running test.

Steps to reproduce the bug

  1. add karma-viewport with your package manager
  2. add viewport into frameworks array in karma.config.js
  3. run test:
    /// <reference types="karma-viewport" />    
    viewport.set(1000, 1000);

Package versions

  • karma-viewport: 1.0.7
  • karma: 5.1.1

System information

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.