【问题标题】:Testing React Form using Axios to post onSubmit method使用 Axios 测试 React Form 以发布 onSubmit 方法
【发布时间】:2020-11-19 17:36:40
【问题描述】:

我是 JavaScript 和测试新手。我使用“npx create-react-app”作为起点。我搜索了论坛,但代码非常不同。

CreatPost.js


import React, { useState } from 'react';
import axios from 'axios';

export default () => {
  const [title, setTitle] = useState('');
  const onSubmit = async event => {
    event.preventDefault();

    await axios.post('http://localhost:4000/posts', {
      title
    });
    // clear title
    setTitle('');
  };

  return (
    <div>
      <form onSubmit={onSubmit}>
        <div className="form-group">
          <label>Title</label>
          <input
            value={title}
            onChange={e => setTitle(e.target.value)}
            className="form-control"
          />
        </div>
        <button className="btn btn-primary">Submit</button>
      </form>
    </div>
  );
};


axios.js 模拟文件

export default {
  get: jest.fn().mockResolvedValue(),
  post: jest.fn().mockResolvedValue()
  };

我根据这里的研究所做的尝试:

CreatePost.test.js


import * as axios from 'axios';
import request from 'supertest';
import CreatePost from '../CreatePost';


it('returns a 201 on successful post', async () => {
  axios.post.mockImplementationOnce(() => Promise.resolve());
  return request(CreatePost)
    .post('/posts')
    .send({ 
      title : 'My first post'
    })
    .expect(201);
});

测试出错

TypeError: Cannot read property 'mockImplementationOnce' of undefined
       5 |
       6 | it('returns a 201 on successful post', async () => {
    >  7 |   axios.post.mockImplementationOnce(() => Promise.resolve());
         |              ^
       8 |   return request(CreatePost)
       9 |     .post('/posts')
      10 |     .send({ 

我肯定感到茫然和困惑。任何工作示例将不胜感激。

使用 axios-mock-adapter 进行第二次尝试
CreatePost.test.js

import CreatePost from '../CreatePost';
import mockedAxios from 'axios-mock-adapter';


it('returns a 201 on successful post', async () => {
  mockedAxios.post.mockImplementationOnce(() => Promise.resolve());
  return request(CreatePost)
    .post('/posts')
    .send({ 
      title : 'My first post'
    })
    .expect(201);
});

TypeError: axios.create 不是函数

  1 | //import request from 'supertest';
  2 | import CreatePost from '../CreatePost';
> 3 | import mockedAxios from 'axios-mock-adapter';
    | ^
  4 |

【问题讨论】:

  • 试试axios-mock-adapter
  • 尝试使用axios-mock-adapter,现在出现新错误。
  • 来给我看,也许在prv msg上
  • 我的尝试被添加到底部的帖子中:Second Attempt with axios-mock-adapter. 它抛出了这个错误:TypeError: axios.create is not a function。另外,我还没有阅读 Stack Overflow 用户指南,所以我不知道如何发送 prv 消息。

标签: javascript reactjs unit-testing axios


【解决方案1】:

这是axios-mock-adapter 的规范用法:

import MockAdapter from 'axios-mock-adapter';

const mock = new MockAdapter(axios);
const resp = 'success';

mock.onGet().reply(201, resp);

但我认为你不知道自己在做什么...... 请先阅读文档,然后再提问。另外,我首先推荐jestenzyme 基础的教程:)

【讨论】:

  • 感谢您的客气话。我已经好几年没有使用 JavaScript 了,因为过去 5 年我一直在使用 C# 和 Dot Net Core 为 HPE 创建服务。我从来没有写过 JavaScript 测试,很抱歉我缺乏知识。我能够使用const mock = new MockAdapter(axios); 并在添加await waitFor(() =&gt; onSubmit()) and expect(onSubmit).toHaveBeenCalledTimes(1); 后使其正常工作此外,Get 将返回 200,成功,Post 将返回 201,已创建。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2023-02-09
  • 2021-07-28
  • 1970-01-01
  • 2018-02-08
  • 1970-01-01
  • 2017-08-30
  • 2021-02-24
  • 1970-01-01
相关资源
最近更新 更多