Can Jest Vue handle loading dynamic imports for snapshot testing?

Having an issue with unit testing a Vue component that dynamically loads its child component. Jest and Vue utils don't seem to render it. Any suggestions on how to tackle this?

Here's the component code:

<template>
  <component :is="component" v-bind="props" />
</template>

<script>
const components = {
  dog: () => import('./dog.vue'),
  cat: () => import('./cat.vue')
}

export default {
  props: { type: String }

  computed: {
    component() {
      return components[this.type]
    }

    props() { ... }
  }
}
</script>

This is how my test looks like:

...
it('renders correctly', async () => {
  const wrapper = mount(Component, { ... })

  expect(wrapper.element).toMatchSnapshot()
})
...

And here's the snapshot file I'm getting:

// Jest Snapshot v1

exports[`Markdown Token renders correctly 1`] = `<!---->`;

Appreciate any help in advance :)

Answer №1

In the initial loading cycle, the dynamic component may not load as expected. To ensure that the lazy-loaded component is imported before checking the snapshot, you can update the props accordingly. In these scenarios, I am resetting the type property to trigger the import of the dynamic component promptly.

An example using Vue utils:

test('render dog component', async () => {
  const wrapper = mount(Component, { ... });

  // Resetting props if 'dog' was already passed
  await wrapper.setProps({ type: '' });
  // Setting it again.
  await wrapper.setProps({ type: 'dog' }); 

  expect(wrapper.element).toMatchSnapshot()
})

An example using Testing library:

test('render dog component', async () => {
  const { html, updateProps } = render(Component, { ... });

  // Resetting props if 'dog' was already passed
  await updateProps({ type: '' });
  // Setting it again.
  await updateProps({ type: 'dog' }); 

  expect(html()).toMatchSnapshot();
})

Update:

It might be beneficial to preload lazy-loaded components before snapshot checks:

test('render dog component', async () => {
  const { html } = render(Component, { ... });

  await Promise.all([import('./dog.vue'), import('./cat.vue')]); 

  expect(html()).toMatchSnapshot();
})

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

Use JavaScript to dynamically populate dropdown list options with array elements

I attempted to populate a dropdown list with array elements using javascript, but I encountered issues. I referred to the following links for assistance: JavaScript - populate drop down list with array use a javascript array to fill up a drop down se ...

Uploading files using Multipart/form-data in Node.js and Express.js

With the removal of express.multipart from the Express 4.x library, what approach would be most effective for managing file uploads in expressjs? ...

Ways to extract the returned AJAX success object from a function

Attempting to extract attribute values, I have assigned an ajax GET request to a variable. The console.log displays the ajax object, but I am encountering difficulty returning the object within the success function. I have tested with: ajaxObj.d ajaxObj.r ...

When I try running my JavaScript code in the console, it works perfectly fine. However, I encounter an error when I attempt

Recently, I added a cool JavaScript code to my website that changes the background of the landing page randomly. Here is the snippet: var bgImages = [ "url('assets/bg/front1.jpg')", "url('assets/bg/fro ...

Can the tooltip of an element be changed while the old tooltip is still visible without having to move the mouse away and then back again?

When I have an HTML anchor element with a tooltip that appears when the mouse is hovered over it, and then I use JavaScript to change the tooltip's text using element.title = "Another Tooltip", the new tooltip text does not immediately update visually ...

Having trouble uploading my confidential npm package to a secure Nexus repository

I have my own personal collection of books and I am looking to share it by publishing an npm package to a private Nexus registry Here is my package.json setup { "name": "@uniqueorganization/the-collection", "version": ...

Discovering ways to align specific attributes of objects or target specific components within arrays

I am trying to compare objects with specific properties or arrays with certain elements using the following code snippet: However, I encountered a compilation error. Can anyone help me troubleshoot this issue? type Pos = [number, number] type STAR = &quo ...

What is the best way to execute a function based on its name, which is provided as a parameter

Is there a better way to call a function by its name, passed as a parameter in JavaScript? Here's my scenario: I have a switch case where I need to set the data for an API ajax call. Once the ajax call is complete, I want to call a specific print func ...

What is the best way to replace testcaferc.json browsers using the command line interface (CLI

Scenario: I am facing a situation where I aim to execute Testcafe in docker within a remote environment that necessitates running Testcafe through its command-line interface. I intend to utilize the .testcaferc file that I use for local testing to avoid m ...

Problem encountered with a form element generating additional input fields upon click of a specific button

My goal is to create a button that dynamically adds email input fields to a form titled "Add Another Email". I have a function in place to trigger this action upon clicking the button, but unfortunately, nothing happens when the button is clicked. Surprisi ...

Is there a way to change or delete this inline javascript using Greasemonkey?

I stumbled upon this script within the head of a website: <script type="text/javascript" > function Ext_Detect_NotInstalled(ExtName,ExtID) { } function Ext_Detect_Installed(ExtName,ExtID) { alert("We have detected an unauthorized extension. Pl ...

Discovering the Newest Product Updates through API Integration

I have a component that displays only the most recent product fetched from an API: const about = ({products}) => { const data = products.attributes console.log(data) return ( <div> <h1>{data.Name}</h1> ...

Leveraging the content delivery network for react-select in a react.js project

I'm having trouble using react-select with cdn. I attempted to download the cdn for react-select but keep encountering an error stating that 'select is not defined'. I also tried downloading the zip package for react-select, but I am unsure ...

Leveraging Jest for simulating AJAX requests in a React application

I’ve been working on a React component that fetches data from the server using AJAX when it mounts. Recently, I’ve been struggling to mock the AJAX call in Jest. I have a feeling that I might be misunderstanding how mocking functions in Jest really wo ...

Troubleshooting issue: AngularJS not receiving NodeJS GET requests

I recently developed a web application for sharing photos. Currently, I am working on a route that is designed to fetch and display the photos of all users from an array. The code for the route is as follows: router.get('/getphotos',function(re ...

Leveraging keyboard input for authentication in Angular

Would it be possible to modify a button so that instead of just clicking on it, users could also enter a secret passphrase on the keyboard to navigate to the next page in Angular? For example, typing "nextpage" would take them to the next page. If you&apo ...

Ways to adjust a specific div within an ng repeat using the value from JSON in AngularJS

When I select a different option from the dropdown menu, such as cities or states, the values are populated from a JSON file. My specific requirement is to hide a button only when the value 'No data' is populated upon changing the dropdown select ...

Retrieve Gridview properties using JavaScript

I need to adjust the font size of my gridview using JavaScript to make it more suitable for printing. What is the best way to change the font size specifically for a gridview using JavaScript? ...

Challenges arise when attempting to authenticate a user with password.js

Currently, I am working on implementing validation using passport.js and ES6. Below is the validation function that I have created: passport.use(new BasicStrategy( function(login, password, callback) { User.findOne({ login: login }).select(&a ...

Using Angular JS to Implement Multi-filtering for Lists

Having trouble with the filter function in Angular JS when trying to filter a list using different links. I've been struggling to get it right even after trying some examples. Can anyone provide guidance on how to correctly filter the list? HTML < ...