Search code examples
javascriptaxiosweb-api-testing

Passing an object to a function to make an API call


I'm creating an API test framework for a project I am working on and I'm trying to set up an test and and create the framework making sure it's DRY.

I've got a JSON object that I would like to pass to my API calling function. I want to be able to pass different JSON objects to this one function.

So each test would have a different JSON object but I would be able to call the same function for the actual API call.

I'm using axios to POST to the endpoint. I've tried googling how to do this but I'm not sure if I'm jut missing something simple or going about this completely wrong. I've tried using JSON.stringify/parse and other ways to pass the object, but fails when being used by axios

Here is the test function:

describe('Reminder', () => {
  it('It should create a reminder', async () => {
    const reminder = {
      title: 'Test Title',
      description: 'Test Description',
      host: 'User One',
      eventLocation: 'Home',
      eventDate: '01-01-2019'
    };

    const response = await reminderService.createReminder(reminder);
    expect(response.status).to.equal(201);
  });

I'm attempting to pass the reminder object to the createReminder function.

And here is that function:

async function createReminder(reminderObject) {
  console.log('this is the obj' + reminderObject);
  const response = await axios.post(`${config.get('baseUrl')}/reminder`, {
    reminderObject
  });

  return response;
}

module.exports.createReminder = createReminder;

Currently I get a 404 when calling the endpoint. and When I console.log() the reminderObject it comes through as [object object].

The purpose to pass a reminder object with missing fields to test the validation of the API.


Solution

  • You are actually sending the object within another object. If you try this instead:

    const response = await axios.post(`${config.get('baseUrl')}/reminder`, {
        ...reminderObject
    });