用 axios 开玩笑测试 React 登录组件

时间:2021-07-08 16:52:26

标签: reactjs testing axios jestjs

我在测试时遇到了很多困难,而且一般来说我是个新手。我有一个使用 React 和 js 以及 axios 的应用程序。我有一个登录组件,其中包含我正在尝试测试的登录方法。

登录组件如下所示:

function Login() {

  const login = () => {
    Axios.post('http://localhost:3001/login', {
      username: username,
      password: password,
    }).then((response) => {
      if (response.data.message) {
        //Stuff
      } else {
        //More stuff
      }
    });

  };

  return (
      <div>A bunch of stuff</div>
  );
}

export default Login;

登录功能似乎运行良好,但我不确定如何使用 axios 编写测试。

import { shallow, configure } from 'enzyme';
import axios from 'axios';
import Login from '../Login';

import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

jest.mock('axios');

describe('Login component', () => {
  describe('login tests', () => {
    const username = 'username';
    const password = 'password';

    beforeEach(() => {
     
      axios.post.mockResolvedValue({});
    });

    it('should call endpoint with given username & password', () => {
      let wrapper = shallow(<Login />);
      wrapper.instance().login = jest.fn();
      wrapper.update();

      login(username, password);

      expect(axios.post).toBeCalledWith('http://localhost:3001/login', {
        username,
        password,
      });
      
    });
  });
});

现在我的错误是“TypeError:无法设置 null 的属性 'login'”,但我确信在这个测试中我做错了很多其他事情。有人可以帮我吗?

0 个答案:

没有答案