Skip to content

Cookbook: mock

Eugene Lazutkin edited this page Nov 26, 2019 · 8 revisions

In order to use io.mock make sure that it is enabled:

// activate the package
io.mock.attach();

See How to include for more details. See mock for the full documentation.

Return a constant value

io.mock('/url', function () {
  return 42;
});

// ...

io.get('/url').then(function (value) {
  console.log('Got:', value);
});
// prints: Got: 42

Redirect

io.mock('/a', function () {
  return io.get('/b');
});

Catch requests by an exact URL

io.mock('/url', function () {
  // return something
});

// ...

io.get('/url').then(function (value) {
  // gets our mocked value
});

io.get('/url/a').then(function (value) {
  // unmocked request
});

Catch requests by a prefix

io.mock('/url*', function () {
  // return something
});

// ...

io.get('/url').then(function (value) {
  // gets our mocked value
});

io.get('/url/a').then(function (value) {
  // gets our mocked value
});

Catch requests by a regular expression

io.mock(/^\/url/, function () {
  // return something
});

// ...

io.get('/url').then(function (value) {
  // gets our mocked value
});

io.get('/url/a').then(function (value) {
  // gets our mocked value
});

Catch requests by a matcher function

const matcher = options =>
  options.method !== 'GET' &&
  /\/url\//i.test(options.url);

io.mock(matcher, function () {
  // return something
});

// ...

io.get('/url').then(function (value) {
  // gets our mocked value
});

io.get('/url/a').then(function (value) {
  // gets our mocked value
});

Remove a mock

In this example, we will removed mocks set up earlier:

io.mock('/url');
io.mock('/url*');
io.mock(/^\/url/);
io.mock(matcher);

Introduce delay

We use timeout of heya-async:

io.mock('/url', function () {
  return timeout.resolve(500, io.Deferred).then(function () {
    return 42;
  });
});

Cascade calls

io.mock('/url', function () {
  return io.get('/a').then(function (value) {
    return io.get('/b', {q: value.id});
  });
});

Simulate a server error

io.mock('/url', function () {
  return io.mock.makeXHR({
    status: 500
  });
});