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.

MSW randomly fails to mock GET request while running tests with karma / jasmine

See original GitHub issue

Environment

Name Version
msw 0.33.3
browser Chrome 92.0.4515.107
OS Mac OS 11.4
Node 14.17.3
npm 7.20.5

Request handlers

handlers.ts

import { rest } from 'msw';
import { units } from './data/units';

const baseUrl = 'http://api.mock';

export const handlers = [
    rest.get(`${baseUrl}/fakerequest`, (req, res, ctx) => {
        return res(
            ctx.status(200),
            ctx.json(units.multiple())
        );
    })
];

browser.ts

import { setupWorker } from 'msw';
import { handlers } from './handlers';

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

test.ts

// This file is required by karma.conf.js and loads recursively all the .spec and framework files

import 'zone.js/testing';
import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';
import {worker} from "./mocks/browser";

worker.start();

declare const require: {
  context(path: string, deep?: boolean, filter?: RegExp): {
    keys(): string[];
    <T>(id: string): T;
  };
};

// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);

Actual request

fake-service.service.spec.ts

import { TestBed } from '@angular/core/testing';

import { FakeServiceService } from './fake-service.service';
import { HttpClientModule } from '@angular/common/http';
import { doesNotReject } from 'assert';

describe('FakeServiceService', () => {
  let service: FakeServiceService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientModule]
    });
    service = TestBed.inject(FakeServiceService);
  });

  it('Should get a response', done => {
    service.fakeCall().subscribe(
      data => {
        expect(data.length).toBeGreaterThan(0);
        done();
      }
    );
  });
});

fake-service.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class FakeServiceService {
  constructor(private httpClient: HttpClient) {}

  public fakeCall = (): Observable<any> => {
    return this.httpClient.get<any>('http://api.mock/fakerequest');
  };
}

Current behavior

Currently, while running tests with karma in a fresh angular project, the tests will randomly fail with a message coming from msw that it Failed to mock GET request as shown in the screenshots below. I haven’t found a way to reproduce this problem as it really seems to happen randomly (sometimes within 5 min, sometimes 10-15min of retrying). This happens both locally as in the CI.

Example repo can be found here

Expected behavior

msw will be able to mock the request

Screenshots

Schermafbeelding 2021-08-06 om 11 20 08 Schermafbeelding 2021-08-06 om 11 24 49

Issue Analytics

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

github_iconTop GitHub Comments

1reaction
KamalAmancommented, Aug 31, 2021

In my case, I though I was running into this issue. However what it turned to be was that the mockServiceWorker.js static dependency was not being properly loaded into the environment and worker.start would never finish resolving because it got a 404 error when loading.

1reaction
kettanaitocommented, Aug 6, 2021

Hey, @DennisOosterling.

Please update to 0.34.0 and update the worker script in your public directory. We’ve improved the error message, and “Failed to mock” is not as ambiguous as before. In reality, error messages like this meant an error in your code (with how the request was made or what kind of response was received). They were rarely related to MSW. It was a misleading error message that led our users to believe it was MSW failing to mock something when it was only propagating an exception from the request/response.

Please, could you put this into a reproduction repository for me to look at? I’m happy to look into this, but I don’t have the capacity to set up example repositories. I hope for your understanding.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Angular testing: mocking a service throwing an error makes ...
on Karma I'm getting an error saying Uncaught [object Object] thrown (this message thrown under a different test).
Read more >
Debugging uncaught requests - Recipes - Mock Service Worker
Debugging uncaught requests · Enable onUnhandledRequest option · Examine the handlers · Verify the worker's scope · Run in debug mode.
Read more >
axios-mock-adapter - npm
axios-mock-adapter. Axios adapter that allows to easily mock requests. Installation. Using npm: $ npm install axios-mock-adapter --save-dev.
Read more >
Stop mocking fetch - Kent C. Dodds
However, msw supports Node anyway for testing purposes. The basic idea is this: create a mock server that intercepts all requests and handle...
Read more >
React hooks (v17.0.3) and Redux handbook using TypeScript ...
This isn't like Karma test runner which will spool up an actual browser to run the tests in. This makes these tests very...
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