Vue项目运行Jest测试报错TypeError: Cannot set property 'content' of null
问题原因
- Jest运行测试时默认使用jsdom模拟浏览器环境,不会加载项目的
index.html入口文件,所以api.js中读取的meta[name="apiBaseUrl"]标签不存在,querySelector返回null。 api.js的逻辑存在书写错误:判断apiBaseUrl为null的分支中,仍然尝试操作null的content属性,直接触发类型错误。该问题不仅出现在测试环境,浏览器运行时如果真的缺失对应meta标签也会导致页面崩溃。
解决方案
1. 优先修复api.js的逻辑错误(必做)
把原来错误的判断逻辑替换为安全的取值逻辑,即使拿不到meta标签也不会报错:
let apiBaseUrl = document.querySelector('meta[name="apiBaseUrl"]'); // 存在meta标签取content属性,不存在直接使用默认接口前缀 const baseURL = apiBaseUrl ? apiBaseUrl.content : '/api/'; let newAxios = axios.create({ headers: { // A fix for IE11 - we need to define Pragma header Pragma: 'no-cache', // 'X-Requested-With': 'XMLHttpRequest' }, withCredentials: true, baseURL: baseURL, paramsSerializer: function (params) { return qs.stringify(params) } });
2. 测试环境模拟meta标签(可选,贴合真实运行环境)
如果需要测试环境和生产环境的配置保持一致,可以在Jest全局前置脚本中提前插入meta标签:
- 新建
jest.setup.js文件,写入以下内容:
const testMeta = document.createElement('meta'); testMeta.name = 'apiBaseUrl'; testMeta.content = '/test-api/'; // 可自定义测试环境的接口前缀 document.head.appendChild(testMeta);
- 在
jest.config.js中添加配置,让Jest运行测试前先执行上述脚本:
module.exports = { // 其他配置保留 setupFiles: ['./jest.setup.js'] }
3. 业务组件测试补充配置
如果后续测试Login这类依赖vuex、vue-router的业务组件,还需要在挂载组件时补充模拟依赖:
import { shallowMount } from '@vue/test-utils' import Login from './Login.vue' describe('Login', () => { it('renders login form', () => { const wrapper = shallowMount(Login, { // 模拟vue实例属性 mocks: { $route: { query: {} }, $router: { push: jest.fn() }, $refs: { form: { validate: jest.fn(() => true) } } }, // 模拟vuex store stubs: ['router-link'], store: { getters: { 'account/isAdministrator': false }, dispatch: jest.fn(() => Promise.resolve()) } }) expect(wrapper.find('.login').exists()).toBe(true) }) })
内容的提问来源于stack exchange,提问作者kb9
相关产品推荐
相关产品推荐

