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

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

问题描述

我想测试 AJAX 方法(vanilla XHR),但我找不到使用 Jest 框架进行测试的方法.我为 Jasmine 找到了 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?

推荐答案

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)

并在测试文件中:

导入'../../__mock__/xhr-mock.js'

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

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