Jest中的XMLHttpRequest测试 [英] XMLHttpRequest testing in Jest

查看:302
本文介绍了Jest中的XMLHttpRequest测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试AJAX方法(普通XHR),但找不到使用 Jest 框架的方法.我找到了茉莉花的mock-ajax.js.问题是我找不到安装方法.

I want to test AJAX methods (vanilla XHR) and I can't find the way to do it with Jest framework. I found mock-ajax.js for Jasmine. The problem is I can't find the way to install it.

是否有更好的方法可以在 Jest 中对Ajax函数进行单元测试?

Is there maybe a better way to unit test Ajax functions in Jest?

推荐答案

笑话api有所更改.这就是我用的.它什么也没做,但是足以渲染我的组件.

The jest api has changed a bit. This is what I use. It doesn't do anything but it's enough to render my components.

const xhrMockClass = () => ({
  open            : jest.fn(),
  send            : jest.fn(),
  setRequestHeader: jest.fn()
})

window.XMLHttpRequest = jest.fn().mockImplementation(xhrMockClass)

并在测试文件中:

import '../../__mock__/xhr-mock.js'

这篇关于Jest中的XMLHttpRequest测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆