javascript - 使用 sinon 模拟 POST 请求的 fetch API,react.js 应用程序的玩笑
问题描述
我想测试在单击按钮时启动的 fetch API 的发布请求。为了模拟 fetch api 请求,我正在使用该sinon
库。假服务器是活动的,但不提供响应 JSON 对象。这里apiUrl
是http://localhost:5000/api/users
,用户数据是{ sid: 1, sname: 'test'}
。
这是 App.test.js 文件
describe('test api',()=>{
let server;
beforeEach(() => {
server = fakeServer.create();
server.respondWith('POST',
apiUrl,
[
200,
{ 'Content-Type': 'application/json' },
JSON.stringify(userData)
]
);
});
describe('app component', () => {
const app = mount(<App />);
beforeEach(() => {
app.find('Button').simulate('click');
});
it('get data from server', done => {
server.respond();
setTimeout(done);
});
it('updates state', () => {
expect(app.state().user).toEqual('user1') // fails
})
});
});
编辑:
应用组件
class App extends Component {
constructor() {
super();
this.state = {
serialNum: ''
user: ''
}
}
submitUrl = async () => {
const postData = { sid: this.state.serialNum, sname: 'something'};
try {
let response = await fetch('http://localhost:5000/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(postData)
});
response = await response.json();
if (result) {
this.setState({ user: response.username});
}
} catch (err) {
console.log('Error:', err);
}
}
render() {
return (
<div className="container">
<div className="col">
<Form>
<FormGroup>
<div className="row input-container">
<FormControl placeholder="Enter value"
onChange={(e) => this.setState({
serialNum: e.target.value
})} />
</div>
<div className="row">
<Button variant="primary"
className="submit-btn"
onClick={this.submitUrl}>Submit</Button>
</div>
</FormGroup>
</Form>
</div>
</div>
);
}
}
export default App;
我在这里想念什么?如果服务器请求成功或失败,我该如何调试?我server.respond()
在模拟按钮单击并要求 Jest 等待服务器通过传递done
参数完成请求后调用。
解决方案
为什么不只是模拟 fetch 函数本身,而不是服务器。所以:
describe('app component', () => {
const app = mount(<App />);
beforeEach(() => {
global.fetch = jest.fn().mockImplementation(() => {
return Promise.resolve(new Response(JSON.stringify({ sid: 1, sname: 'test' })));
});
app.find('Button').simulate('click');
});
it('updates state', () => {
expect(app.state().user).toEqual('user1') // fails
})
});
请记住,您正在这里测试数据获取后的状态更改,只需模拟 fetch 函数就足以充分测试您的逻辑。
推荐阅读
- https - 如何解决 HTTP 状态 400 - 错误请求
- javascript - TypeError:self.webSocketIo.listen 不是函数
- sql - 从当前月份动态向后旋转 12 个月
- python - “pvlib”模块中缺少“逆变器”属性?
- sharepoint - sharepoint 2019 无法从第二个域添加用户
- node.js - 如何让发布请求等到 req.body.value 在运行下一个函数之前加载
- rust - 当我们永远无法同时拥有这两者时,我们如何将可变引用强制转换为不可变引用?
- dynamics-crm - 逻辑应用程序 - 如何从 dynamicax API 连接中获取环境信息
- row-level-security - 使用行级策略进行 Supabase 更新
- c - 可以在 C 中打印一串不可打印的字符