简体   繁体   中英

How to assert that app sends correct data to API server with POST request

I am writing React.js application talking to API server. I have read tons of articles on how to mock these calls and send some fake response from API. I can do testing using @testing-library/react, I can easily mock axios with axios-mock-adapter and test fetch requests using HTTP GET method. But I cannot find anywhere how to make sure that my app, when it sends some POST request, sends correct data to API, ie that my app sends json payload with eg "id" field, or "name" field set to "abc", or something like this.

I am new to React.js. Please advise how to make tests asserting what the app sends to API. Is it possible?

Let's say that I have a function named doSomething, like below, called with onClick of some button.

const doSomething = async (userId, something) => {
    try {
        await REST_API.post('doSomething', {
            user_id: userId,
            something: something
        });
        return true;
    } catch (error) {
        window.alert(error);
        return false;
    }
};

REST_API above is axios instance.

How can I ensure that the I (or some other developer) didn't make a typo and didn't put "userId" instead of "user_id" in the payload of the request?

If you have to be sure you call correctly the api, I'd use jest as follow:

jest.mock('axios', () => ({
  post: jest.fn(),
}));

describe('test', () => {
  it('doSomething', () => {
    const userId = 123;
    const something = 'abc';
    doSomething(userId, something);
    expect(axios.post).toBeCalledWith(
      'doSomething', {
        user_id: userId,
        something,
      },
    );
  });
});

or if you use instance, define it in another file ( axios_instance.js ) and using the follow test:

jest.mock('./axios_instance', () => ({
  instance: {
    post: jest.fn(),
  },
}));

describe('test', () => {
  it('doSomething', () => {
    const userId = 123;
    const something = 'abc';
    doSomethingInstance(userId, something);
    expect(instance.post).toBeCalledWith(
      'doSomething', {
        user_id: userId,
        something,
      },
    );
  });
});

For your need I would use Swagger and its tooling. You would kill three birds with one stone :

That way you have a rock solid Frontend + Backend + Documentation combo ..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM