我是 JavaScript 和测试新手。我使用“npx create-react-app”作为起点。我搜索过论坛,但代码非常不同。
CreatePost.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({
我肯定感到茫然和困惑。任何工作示例将不胜感激。
一只萌萌小番薯
相关分类