Msw: Angular MSW (Jest)

Created on 10 Jul 2020  路  13Comments  路  Source: mswjs/msw

First of all, thank you for writing this library.
It's been a joy to use it on a demo project.

Environment

| Name | Version |
| ---- | ------- |
| msw | ^0.19.5 |
| node | v12.18.0 |
| OS | Windows 10 |

Request handlers

// handlers
import { rest } from 'msw';

export const handlers = [
    rest.get('https://rickandmortyapi.com/api/character', (req, res, ctx) => {
        console.log('MSW Handler');
        return res(
            ctx.status(202, 'Mocked status'),
            ctx.json({
                message: 'Mocked response JSON body',
            }),
        );
    }),
];

// server
import { setupServer } from "msw/node";
import { handlers } from "./handlers";

export const server = setupServer(...handlers);

Actual request

export class RickAndMortyService {
    constructor(private http: HttpClient) {}

    getCharacters() {
        return this.http.get('https://rickandmortyapi.com/api/character');
    }
}

Current behavior

The requests reaches the MSW handler, but Angular doesn't receive the response.

Expected behavior

I would expect that the Angular HTTP client handles the request/response correctly.
This only happens with Angular + Jest, with Jasmine/Karma Angular does receive the response.

Observations

What I see is that Angular uses addEventListener to receive XHR responses.
When I rewrite this line, by just using the onload function, the response gets handled correctly.
I have no idea why, and I'm not sure where to look.
I was wondering if you have seen this behavior before with other libraries.

const onLoad = () => {/* Angular's implementation */}

// onLoad is never invoked
// xhr.addEventListener('load', onLoad);     

// this works
xhr.onload  = onLoad;

The Angular source code can be found here

An older reproduction of this can be found here

To reproduce:

  • clone
  • run yarn
  • run yarn test:jest to run the jest test
  • run yarn test to run the jasmine test
bug node

Most helpful comment

Tim already wrote a blog post on the topic: https://timdeschryver.dev/blog/using-msw-in-an-angular-project

All 13 comments

Hey, @timdeschryver! Thanks for reporting this.

I confirm that there's an issue in the node-request-interceptor library (the one that powers requests interception in NodeJS). Specifically, when you attach an event listener via xhr.addEventListener(), the patched XMLHttpRequest instance doesn't call the given event handler (although all the interception/mocking is still at place). This results into a request hanging forever, which is not an expected behavior.

I'll tackle this on the NRI side and let you know once I have more details.

I have tried the code and the handler is called but the response never arrived

I've found the root cause of the issue and tackling this at the moment. Will issue a pull request soon.

The issue is fixed in [email protected]. The update of that dependency will propagate to msw in the next release (0.20.0). You can still try if 0.3.1 resolves the issue by installing it locally. Thanks.

Wow, that was quick - thanks @kettanaito !
I will give this a try next week.

It's time to introduce MSW to the Angular community 馃檶

@timdeschryver, glad to help. I'm super excited for Angular community to adopt MSW! Looking forward to hear more interesting use-cases.

I think that angular example should be created. What do you think ?

Tim already wrote a blog post on the topic: https://timdeschryver.dev/blog/using-msw-in-an-angular-project

Okok I see, but maybe we could add angular project example here in this way with new updates we are pretty sure that they will work on angular and react. On the CI there is a step that run examples with new version of MSW

Definitely agree. We should have an official Angular example 馃憤 You can use the React REST API example as a reference.

Feel free to assign that to me if you'd like.
I'm happy to "give back" 馃槈

@kettanaito I just verified that it works with [email protected].
Thanks again!

@timdeschryver so happy to hear that!
Sure, we'd be most grateful if you helped us with the Angular example. You can take a look at the Examples repository and issue a pull request. We strive towards including a minimum example, the one that contains the MSW integration and one/two requests + unit and integration tests. Please reference the existing examples to grasp the idea. I'd be glad to assist you during the code review 馃憤

Was this page helpful?
0 / 5 - 0 ratings