huturen / http-request-mock

Intercept & mock http requests issued by XMLHttpRequest, fetch, nodejs https/http module, axios, jquery, superagent, ky, node-fetch, request, got or any other request libraries by intercepting XMLHttpRequest, fetch and nodejs native requests at low level.

Home Page:https://huturen.github.io/http-request-mock-docs/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Cannot mock same URL multiple times with different status

aminpaks opened this issue · comments

Hi folks,

I can't seem to find a way to mock a URL multiple specific times with different statuses. The dynamic response works only for the body, and not status, am I missing something?

Update:
This is the issue, we only support returning the response, and getting the status from the main options instead of allowing the lazy function returns the status including the body.

Hi @aminpaks,

You can set status code in the response option by this.status = xxx, try the code below:

mocker.mock({ 
  url: 'https://test.api.com/', 
  response(req) {
    if (/200/.test(req.url)) {
      this.status = 200; // set status here
      return { code: 0, msg: 'ok' };
    }

    this.status = 404; // and here
    return 'Not Found';
  }
});

If the URL contains 200, the HTTP status code will be returned as 200; otherwise, it will be returned as 404.

image

Thanks for the quick response!