我是 JavaScript 和测试新手。我使用“npx create-react-app”作为起点。我搜索过论坛,但代码非常不同。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() };我根据这里的研究尝试过: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);});测试中的错误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({ 我肯定感到茫然和困惑。任何工作示例将不胜感激。
1 回答
一只萌萌小番薯
TA贡献1795条经验 获得超7个赞
这是以下的规范用法axios-mock-adapter:
import MockAdapter from 'axios-mock-adapter';
const mock = new MockAdapter(axios);
const resp = 'success';
mock.onGet().reply(201, resp);
但我认为您不知道自己在做什么...请先阅读文档,然后再提出问题。另外,我首先推荐教程jest和enzyme基础知识:)
添加回答
举报
0/150
提交
取消