Jest Test - Uncaught TypeError: Unable to create range using document.createRange

my unique test

import VueI18n from 'vue-i18n'
import Vuex from "vuex"
import iView from 'view-design'
import {mount,createLocalVue} from '@vue/test-utils'
// @ts-ignore
import FormAccountName from '@/views/forms/FormAccountName/FormAccountName'
const localVue = createLocalVue()
localVue.use(Vuex)
localVue.use(iView)
localVue.use(VueI18n)
describe('test description',()=>{
    test('test example',async ()=>{
        const wrapper = mount(FormAccountName,{
            localVue,
            mocks: {
                $t: () => 'this is a label',
                formItems: {
                    name: '<a>'
                }
            },
        })
        expect(wrapper).toMatchSnapshot()
    })
})

unique error message

The snapshot was generated successfully, but an unexpected error occurred

[Vue warn]: Error in nextTick: "TypeError: document.createRange is not a function"

found in

---> <Tooltip>
       <ErrorTooltipTs>
         <ValidationProvider>
           <FormRow>
             <ValidationObserver>
               <FormWrapper>
                 <FormAccountNameUpdateTs>
                   <Root>

Even though I initialized the iView tag, an error occurred. I am unsure of what went wrong. Can someone offer assistance?

Answer №1

let newRange = document.createRange();
newRange.setStart = () => {}
newRange.setEnd = () => {}
//@ts-ignore
newRange.commonAncestorContainer = {
  nodeName: "HTML",
  ownerDocument: document,
}

Answer №2

To include the following configuration mock code, add it to either pollyfill.js or testSetup:

global.document.createRange = () => ({
        setStart: () => {},
        setEnd: () => {},
        commonAncestorContainer: {
            nodeName: 'BODY',
            ownerDocument: document
        },
        createContextualFragment: jest.fn
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The submit button remains disabled even with valid form data (vee-validate)

I'm trying to implement a feature where the submit button on my form remains disabled until valid data is entered in all fields. However, even after entering correct data, the submit button stays disabled. Code Snippet: <div id="app"> <fo ...

Implementing state management with Vue.js

After creating a login page and setting conditions to display different NAVBARs based on the user's login status, I encountered an issue where the rendering seemed to be delayed. In the login process, I utilized local storage to store a token for auth ...

What is the most effective way to extract data that includes an array within it?

const flightList = [{ number: 343, from: "Singapore", to: "India", upgradeTypes: ["Economy to Premium Economy", "Economy to Business Class"] }, . { number: 363, from: "Chennai", to: "Sing ...

What is the best way to depict object key replacements within a Typescript definition?

I currently have these types: type PossibleKeys = number | string | symbol; type ValueOf<T extends object> = T[keyof T]; type ReplaceKeys<T extends Record<PossibleKeys, any>, U extends Partial<Record<keyof T, PossibleKeys>> = ...

Incorporating Moment.js into React Native Typescript for Enhanced Date and

I am currently facing an issue while using Moment.js and React Native to work with date and time. My code snippet below showcases how I am attempting to utilize the library. import * as React from 'react'; import { Text, View, StyleSheet } from ...

When in debug mode, the Unit Test Sessions Window automatically closes

After choosing an NUnit test in the Unit Test Sessions window and clicking debug, the window seems to vanish. Although my breakpoints are being hit, the Unit Test Sessions window does not reappear until the test produces a result or I end the debugging s ...

Angular 6 - The requested resource does not have the necessary 'Access-Control-Allow-Origin' header

I am currently working on an Angular 6 project that includes a service pointing to server.js. Angular is running on port: 4200 and Server.js is running on port: 3000. However, when I try to access the service at http://localhost:3000/api/posts (the locat ...

Is there a way to execute a code snippet just once when focusing on a specific field?

<form id="myForm"> <label for="fname">First name:</label><br> <input type="text" id="fname" name="fname"><br> <label for="mname">Middle name:</label> ...

How to Send an Ajax Request from a Vue.js Application to WordPress

I've designed a custom page template to seamlessly integrate a vue app into an existing website <?php /* * Template Name: Registration Form */ get_header(); ?> <div id="app"></div> <?php get_footer(); ?> After some ...

Error: Vue.js application requires the "original" argument to be a Function type

I am facing an issue when trying to call a soap webservice using the 'soap' module in my Vue SPA. Strangely, I encounter an error just by importing the module. Despite my extensive search efforts, I have not been able to find a solution yet. Her ...

Angular: detecting mobile status within template

Often in my templates, I find myself repeating this type of code: <custom-button [align]="isMobile() ? 'center' : 'left'"></custom-button> This also requires me to include a method in each component to determine w ...

Mastering the use of hover event handler in Vue.js is crucial for effective development

I'm currently teaching myself Vue.js and could use some assistance. I'm working on event handlers at the moment. I'm trying to make the red box expand by 100px when hovered over. It works fine when I change hover to click, but for some reaso ...

PhpStorm 2019.2 introduces Material UI components that have optional props instead of being mandatory

My PhpStorm 2019.2 keeps showing me a notification that the Button component from Material UI needs to have an added href prop because it is required. However, when I refer to the Material UI API, I see something different. Take a look at this screenshot: ...

Vue: Opening all GmapInfoWindows simultaneously upon clicking one

I am working on a platform where users can report crimes or incidents by placing markers on a map. These markers with all the reported incidents are then displayed on another map. Each marker has an info window that provides details about the incident and ...

Enforcing uniform data types in nested objects in TypeScript

Currently, I am in need of generating a list of constants. For instance, const Days = { YESTERDAY: -1, TODAY: 0, TOMORROW: 1, } I am looking for a method to restrict the types of all properties within Days. In other words, if I attempt to add a pr ...

The @click directive in vuex does not function properly within the Vue component

This content is from my online shop. getters: { getFormattedUsers (state) { state.users.forEach(v => { v.fullname = `${capitalize(v.fname)} ${capitalize(v.lname)}` v.created_from_now = moment(v.created_at).fromNow() v.approve_but ...

Adding local JavaScript to a Vue component is a great way to enhance its functionality

I am currently working on integrating a homepage concept (Home.vue) into my project. The design is based on a template that I purchased, which includes CSS, HTML files, and custom JavaScript. While most of the CSS has been successfully imported, I am havin ...

Configuring a NestJS application to establish a TypeOrm connection using environment variables and @nestjs/config

Looking for the best way to set up a NestJS database using a .env file in compliance with legal requirements. The goal is to utilize the @nestjs/config package to import .env variables and incorporate them into the TypeOrmModule. It appears that utilizing ...

Understanding the concept of a "class variable" in Typescript when referring to a variable that belongs to another class

When we declare a variable at the class level and assign it the type of another class, such as in the following code: let greeter: Greeter; //line 1 greeter = new Greeter("world"); What is contained within 'greeter' on line 1? ...

Custom JSX element failing to include children during addition

I have created a unique component in JSX, like this: const CustomComponent = ({content}) => { return <div className={content}></div>; } I am using it as follows: <CustomComponent content={"xyz"}> <p>Some additio ...