【发布时间】: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