我正在基于 Vue 的项目编写测试,并且我是 Framwork Jest 和 Vue 测试 Utils 的新手,我还没有找到类似问题的解决方案,我尝试过几个组件,但错误总是类似
示例.test.js
import { shallowMount } from '@vue/test-utils'
import Foo from './Foo.vue'
describe('Foo', () => {
it('renders a div', () => {
const wrapper = shallowMount(Foo)
expect(wrapper.contains('div')).toBe(true)
})
})
● Test suite failed to run
TypeError: Cannot set property 'content' of null
6 | let apiBaseUrl = document.head.querySelector('meta[name="apiBaseUrl"]');
7 | if(!apiBaseUrl) {
> 8 | apiBaseUrl.content = '/api/';
| ^
9 | }
10 |
11 | let newAxios = axios.create({
api.js
let apiBaseUrl = document.querySelector('meta[name="apiBaseUrl"]');
if(!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: apiBaseUrl.content,
paramsSerializer: function (params) {
return qs.stringify(params)
}
});
索引.html
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<meta name="apiBaseUrl" content="<%= VUE_APP_BASE_API_URL %>" >
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title>test</title>
</head>
这是我的组件的真实代码,
允许用户识别
<template>
<div class="login">
<div class="login--headline">
<router-link tag="a" :to="{name: 'home'}" class="login--`headline-logo">`
*****
</div>
</template>
<script>
import {mapActions, mapGetters} from 'vuex';
import ResetPassword from "@components/account/PasswordReset";
import RegisterUser from "@components/account/RegisterUser";
export default {
name: "Login",
components: {
RegisterUser,
******
ResetPassword
},
data() {
return {
currentMode: "login",
passwordForgotMode: false,
registerMode: false,
email: "",
password: "",
rememberMe: false,
emailRules: [
v => !!v || 'E-Mail wird benötigt',
],
passwordRules: [
v => !!v || 'Passwort wird benötigt',
],
valid: false,
}
},
computed: {
...mapGetters({
isAdministrator: 'account/isAdministrator',
})
},
methods: {
...mapActions({
handleLogin: 'account/handleLogin',
addSnackbarFromError: 'app/addSnackbarFromError',
}),
send() {
if (this.$refs.form.validate()) {
this.handleLogin({
rememberMe: this.rememberMe,
email: this.email,
password: this.password,
})
.then(() => {
window.localStorage.setItem('logged_in', true);
if (this.$route.query.redirect) {
this.$router.push(decodeURIComponent(this.$route.query.redirect));
} else {
if (this.$store.getters["account/isAdministrator"]) {
this.$router.push({name: 'userNotificationsOverview'});
} else {
this.$router.push({name: 'startingSite'});
}
}
})
.catch((error) => {
this.password = '';
this.addSnackbarFromError(error)
})
}
}
}
}