Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you verify that a request was made with axios-mock-adapter?

I am using https://github.com/ctimmerm/axios-mock-adapter

I would like to know how can I verify that an endpoint was actually called by the system under test.

In this example:

var axios = require('axios');
var MockAdapter = require('axios-mock-adapter');

// This sets the mock adapter on the default instance
var mock = new MockAdapter(axios);

// Mock any GET request to /users
// arguments for reply are (status, data, headers)
mock.onGet('/users').reply(200, {
  users: [
    { id: 1, name: 'John Smith' }
  ]
});

How could I tell if a get on '/users' was called?

I am looking for something similar to what you can do in Jest:

expect(mockFunc).toHaveBeenCalledTimes(1)

I realise I can use some custom logic when using a function to reply, and setting a local variable indicating if the request has been made. I was just wondering if there was a cleaner way of doing this.

like image 743
Daryn Avatar asked Dec 08 '17 14:12

Daryn


People also ask

How does Axios mock adapter work?

AXIOS Mock adapter allows you to call API in the test file and you can define the expected response according to your need or the same response which you are getting while calling actual API.

How do you mock Axios in mocha?

Show activity on this post. import axios from 'axios'; export async function main() { const URL = 'test url'; const secretKey = 'Test key' const response = await axios. get(URL, { headers: { 'Content-Type': 'application/json', 'KEY': secretKey }, }); I want to write my test case in spec/test.


1 Answers

Note: This answer is now outdated, see this answer by Laszlo Sarvold instead.


axios-mock-adapter does not appear to have this functionality built in to it, however if you are using jest, you can use jest.spyOn.

For your example above

let spy = jest.spyOn(axios, "get");
//run http request here
expect(spy).toHaveBeenCalled();

Note: depending on what you are using, you may have to wrap your expect statement in setTimeout(function, 0) for it to work properly

like image 76
Perogy Avatar answered Oct 11 '22 11:10

Perogy