Angular MSW (Jest)
See original GitHub issueFirst 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
Issue Analytics
- State:
- Created 3 years ago
- Reactions:1
- Comments:13 (12 by maintainers)
Top GitHub Comments
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