Cypress intercept 404 when trying to get local json file

44 Views Asked by At

I'm writing a component test in Cypress for an Angular app. This component on init reads a local json file using a GET like this (this.http is the HttpClient instance):

ngOnInit(): void {
    this.http
        .get<LibraryDynamicData[]>('assets/libraries.json')
        .pipe(take(1))
        .subscribe(...);
}

In the test I tried to stub this call using cy.intercept with no result. This is what I have

it('should get libraries data', () => {
    cy.intercept('assets/libraries.json', []).as('libraries');

    cy.mount(AppComponent, { imports: [AppModule] }).then(() => {
        cy.wait('@libraries').then(interception => {
            assert.isNotNull(interception.response.body, 'Data received');
            ...
        });
    });
});

I get the following error as if Cypress didn't intercept the request.

Cypress error

I also tried to change the url using wildcards like **/libraries.json with no success. What am I doing wrong and how can I stub that call?

1

There are 1 best solutions below

0
Wilt On

To stub a json body you will have to do like so:

cy.intercept('/projects', {
  body: [],
}).as('libraries');

Check also the docs here on how to stub a static response.