使用Moxios测试Axios请求时遇TypeError: adapter属性未定义
解决moxios调用
moxios.install()时的TypeError: Cannot read property 'adapter' of undefined错误 我在使用老版本的axios和moxios时也踩过这个坑,结合你给出的版本(axios@0.16.2、moxios@0.4.0),问题出在老版本的moxios不会自动绑定全局的axios实例上。
为什么会报错?
moxios的核心是替换axios的adapter来拦截HTTP请求,但0.4.0版本的moxios没有自动识别全局导入axios的能力。如果你直接调用moxios.install()不传参数,它找不到要修改的adapter属性,就会抛出这个"Cannot read property 'adapter' of undefined"的错误。
怎么解决?
很简单,只需要在调用install和uninstall时,把你导入的axios实例传进去就行:
- 在
beforeEach钩子中,把moxios.install()改成moxios.install(axios) - 一定要在
afterEach里加上moxios.uninstall(axios),这样测试结束后能清理moxios对axios的修改,避免影响其他测试用例
修正后的完整代码示例
import axios from 'axios' import moxios from 'moxios' import sinon from 'sinon' import { equal } from 'assert' describe('mocking axios requests', function () { describe('across entire suite', function () { beforeEach(function () { // 显式传入axios实例,让moxios能找到对应的adapter moxios.install(axios) }) afterEach(function () { // 清理moxios的修改,保证测试用例隔离 moxios.uninstall(axios) }) it('should intercept and mock a GET request', function (done) { // 拦截指定URL的请求并返回模拟响应 moxios.stubRequest('/target-api', { status: 200, response: { data: '模拟返回的数据' } }) axios.get('/target-api') .then(function (response) { equal(response.data, '模拟返回的数据') done() }) .catch(function (err) { done(err) }) }) }) })
这样调整后,moxios就能正确关联axios实例,替换adapter实现请求拦截,你的测试用例就能正常运行了。
内容的提问来源于stack exchange,提问作者Leon Gaban
相关产品推荐
相关产品推荐

