使用玩笑来测试React服务

时间:2018-12-26 16:04:51

标签: reactjs jestjs

是否可以使用笑话来测试服务? 我正在尝试这样做,但是测试似乎无法运行。

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

it('login user', () => {
  return postAuthUser({ username: 'user', password: 'password' }).then( data => {
    expect(data).toEqual({});
  });
});

我有这个,我正在尝试使用一项服务,但是由于某种原因它无法正常工作。

1 个答案:

答案 0 :(得分:0)

我假设您的postAuthUser的{​​{1}}方法使用authService就像这样:

axios

authService.ts

单元测试:

import axios from 'axios';

export async function postAuthUser(auth) {
  return axios.post('https://github.com/mrdulin', auth);
}

覆盖率100%的单元测试结果:

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

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

describe('authService', () => {
  describe('#postAuthUser', () => {
    it('login user', () => {
      (axios.post as jest.MockedFunction<typeof axios.post>).mockResolvedValueOnce({});
      return postAuthUser({ username: 'user', password: 'password' }).then(data => {
        expect(data).toEqual({});
        expect(axios.post).toBeCalledWith('https://github.com/mrdulin', { username: 'user', password: 'password' });
      });
    });
  });
});

这是完整的演示: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/53934331

相关问题