Test suite failed to run TypeError: Cannot set property 'content' of null Running in Jest

Viewed 629

I am writing a test on a Vue based project, and I am new to the Framwork Jest and Vue testing Utils, I have not found solutions for similar problems, I have tried with several components but the error is always similar

exemple.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)
    }
});


index.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>

this is the real code of my Component , that allows the User to identify

<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)
                        })
                }
            }
        }
    }
1 Answers

When testing a component in Jest, that component is mounted standalone, and the DOM from other components or from outside the Vue application will not be available. Only the DOM from the component itself, and its children will be available.

In this case, I'd suggest to find another way to pass the base URL to your component, via for example a prop, or to have a fallback URL for your tests if document.querySelector() returns NULL.

Related