question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Using MSW with Karma

See original GitHub issue

Environment

Name Version
msw 0.21.3
browser Chrome Headless 86.0.4240.183
OS Mac OS 10.15.6

Request handlers

Added custom header to make sure the service worker is allowed.

// karma.conf.js
const path = require( 'path' );

module.exports = function( config ){
    config.set( {
        basePath: path.resolve( '.' ),
        frameworks: [ 'mocha', 'chai' ],
        client: {
            chai: { includeStack: true },
            mocha: { ui: 'bdd' }
        },
        customHeaders: [
            {
                match: '.*.html',
                name: 'Service-Worker-Allowed',
                value: '/'
            }
        ],
        files: [
            `test/**/${ specs }.spec.js`
        ],
        browsers: [ 'ChromeHeadless' ],
        singleRun: true
    } );
};

All files are located in /test including mockServiceWorker.js, installed via npx msw init test.

// handlers.js
const { rest } = require( 'msw' );

export const handlers = [
    rest.get( '/foo', async ( response, request, context ) => response( context.json( { foo: 123 } ) ) )
];
// worker.js
const { setupWorker } = require( 'msw' );
import { handlers } from './handlers';

export const worker = setupWorker( ...handlers );

Actual request

// foo.spec.js
const { expect } = require( 'chai' );
import { worker } from './worker';

describe( 'Fetching foo', function(){
    this.beforeAll( () => worker.start() );
    this.afterAll( () => worker.stop() );

    it( 'should handle foo', function(){
        return fetch( '/foo' ).then( ( response ) => response.json() ).then( function( data ){
            expect( data ).to.deep.equal( { foo: 123 } );
        } );
    } );
} );

Current behavior

ERROR: '[MSW] Failed to register a Service Worker for scope ('http://localhost:9876/') with script ('http://localhost:9876/mockServiceWorker.js'): Service Worker script does not exist at the given path.

Did you forget to run "npx msw init <PUBLIC_DIR>"?

Learn more about creating the Service Worker script: https://mswjs.io/docs/cli/init'

I have tried tweaking options within worker.start(), including changing the url and scope, and using findWorker, which never seemed to execute.

Expected behavior

I expect the service worker to intercept the request.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:16 (7 by maintainers)

github_iconTop GitHub Comments

4reactions
jeffrosecommented, Nov 10, 2020

In my monorepo project, karma and its plugins were all hoisted to the root node_modules. It’s not always clear to me why yarn chooses to hoist some modules but not others. You could add a nohoist entry to your package.json.

"workspaces": {
  "packages": [
    "examples/*"
  ],
  "nohoist": [
    "**/karma*"
  ]
}
2reactions
kettanaitocommented, Nov 11, 2020

The nonoist option is what solved the issue. Thank you, @jeffrose!

We now have an official Karma usage example. Please refer to it if you’re having troubles setting up Karma and MSW.

Thanks everybody for contribution on this ❤️

Read more comments on GitHub >

github_iconTop Results From Across the Web

Using MSW (Mock Service Worker) in an Angular project
Using MSW to mock your server in an Angular project. ... This file is required by karma.conf.js and loads recursively all the .spec...
Read more >
Examples – MSW - Mock Service Worker
Each example in this section contains a complete showcase of Mock Service Worker usage in development, unit, and E2E tests. A great place...
Read more >
Karma · Enzyme - GitHub Pages
Using enzyme with Karma​​ Karma is a popular test runner that can run tests in multiple browser environments. Depending on your Karma setup,...
Read more >
Mock Service Worker on Twitter: "Imagine writing a single API ...
Imagine writing a single API mock definition and then using it for: - Unit tests (Jest, mocha, karma, etc.) - E2E tests (Cypress,...
Read more >
msw-requirejs - npm
Using msw with Karma +Require.js is a good use case for this package, as well as any application using Require.js.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found