我是 JavaScript 和測(cè)試新手。我使用“npx create-react-app”作為起點(diǎn)。我搜索過論壇,但代碼非常不同。CreatePost.jsimport 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() };我根據(jù)這里的研究嘗試過:CreatePost.test.jsimport * 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);});測(cè)試中的錯(cuò)誤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 發(fā)布 onSubmit 方法測(cè)試 React Form
瀟瀟雨雨
2023-08-18 10:01:29