【问题标题】:Test output data with input data in jest enzyme用开玩笑酶中的输入数据测试输出数据
【发布时间】:2021-07-05 09:56:12
【问题描述】:

我正在尝试测试登录用户的 API 调用。现在我想要发送email and password 作为输入并期望对象带有{ success: true, message: 'logged in'}。在我目前的测试中,我可以使用输入 { success: true, message: 'logged in' } 进行测试,但不能使用 email and password

以下是我在单独文件中的 api 调用。

import axios from 'axios';
export function authService(user, apiEndpoint) {
  return axios.post(`http://localhost:3000/api/v1/${apiEndpoint}`,
    user,
    {
      headers: {
        'Content-Type': 'application/json',
      }  
    }
  )
  .then(response => {
    return response;
  })
  .catch(error => {
    return error;
  });
}

这是 axios 的模拟文件。

module.exports = {
  post: (apiEndpoint, data) => {
    console.log(data) // returns { email: 'blah@email.com', password: '123123', } which I want.
    return Promise.resolve({
      success: true,
      message: 'logged in',
    });
  }
};

这是测试。

it('a post request should be made', () => {
    const loginSpy = jest.spyOn(axios, 'post');
    authService({ email: 'blah@email.com', password: '123123', }, 'login') // authService expects email and password as input.
        .then(response => response)
        .catch(error => error)
        .finally(() => {
            console.log(loginSpy.mock.results[0].value); // this returns Promise { { success: true, message: 'logged in' } } **this is what I want to test**
            expect(loginSpy).toHaveBeenCalled();
            // expect(loginSpy.mock.results[0].value).resolves().toEqual({ // I tried this but it fails
            //  success: true,
            //  message: 'logged in',
            // });
            // expect(loginSpy.mock.calls[0][1]).toEqual({ // This is passed only if I pass { success: true, message: 'logged in' } to authService but authService does not expect this kind of object.
            //  success: true,
            //  message: 'logged in.',
            // });
        })
  });

上面的测试用例中对所有内容都进行了注释。请帮助我测试 API 调用的输入和输出。我该怎么做?

【问题讨论】:

  • 你不调用解析/拒绝,你需要返回或等待期望,因为它是异步的。阅读jestjs.io/docs/asynchronous#resolves--rejects。但是您为什么要尝试测试帖子 返回 的内容 - 这在测试中不受控制吗?那时你只是在测试测试替身——你有理由认为它不会返回你配置的内容吗?您还展示了一个经典的模拟问题:您的 Axios.post 测试替身返回的东西看起来不像 npmjs.com/package/axios#response-schema
  • 我不建议将来自 Axios 的拒绝转换为解决错误的承诺,因为这样下游的所有内容都必须检查“这是解决了结果还是错误?”而是解决或拒绝。

标签: javascript jestjs mocking enzyme


【解决方案1】:

如果您使用jest.spyOn() 来监视和模拟axios.post() 方法及其解析值。您不需要使用 __mocks__/axios.js 模拟文件。为避免混淆,请勿将它们一起使用。

例如

authService.ts:

import axios from 'axios';

export function authService(user, apiEndpoint) {
  return axios
    .post(`http://localhost:3000/api/v1/${apiEndpoint}`, user, {
      headers: {
        'Content-Type': 'application/json',
      },
    })
    .then((response) => {
      return response;
    })
    .catch((error) => {
      return error;
    });
}

authService.test.ts:

import axios from 'axios';
import { authService } from './authService';

describe('68242850', () => {
  it('should return response', async () => {
    const postSpy = jest.spyOn(axios, 'post').mockResolvedValueOnce({
      success: true,
      message: 'logged in',
    });

    const actual = await authService({ email: 'blah@email.com', password: '123123' }, 'login');
    expect(actual).toEqual({ success: true, message: 'logged in' });
    expect(postSpy).toBeCalledWith(
      'http://localhost:3000/api/v1/login',
      { email: 'blah@email.com', password: '123123' },
      {
        headers: {
          'Content-Type': 'application/json',
        },
      }
    );
    postSpy.mockRestore();
  });

  it('should handle error', () => {
    // you can figure it out based on above exmple
  });
});

单元测试结果:

 PASS  examples/68242850/authService.test.ts (9.331 s)
  68242850
    ✓ should return response (4 ms)
    ✓ should handle error

----------------|---------|----------|---------|---------|-------------------
File            | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------------|---------|----------|---------|---------|-------------------
All files       |      80 |      100 |   66.67 |      80 |                   
 authService.ts |      80 |      100 |   66.67 |      80 | 14                
----------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        10.49 s

【讨论】:

    猜你喜欢
    • 2019-09-13
    • 2019-02-27
    • 1970-01-01
    • 2023-03-27
    • 2018-07-28
    • 1970-01-01
    • 2018-10-05
    • 2018-07-22
    • 2021-01-26
    相关资源
    最近更新 更多