Try out various scenarios using propsdata within Vue.js

In my component, there's a button that is displayed only when an article.link prop is not empty. I need to write a test to verify if the button is rendered when article.link has a value and another test for when it is empty.

a.btn.plutus_btn-primary.round( v-if="hasArticleLink" target='_blank' :href="articleLink") Start Shopping Now

The hasArticleLink computed property returns true when the link is not empty.
The unit test implementation is as follows:

    it("should not render the link button when article doesn't have a link", () => {
    wrapper = mount(MerchandisingArticle, {
      propsData: {
        article: {
          link: ""
        }
      }
    });
    expect(wrapper.find("a").exists()).toBe(false);
  });
  it("renders the linked button when article has a link", () => {
    wrapper = mount(MerchandisingArticle, {
      propsData: {
        article: {
          link: "https://google.com"
        }
      }
    });
    expect(wrapper.find("a").exists()).toBe(true);
  });  

The current approach works well, but I'm exploring if there's a more efficient way to handle these two opposite cases without having to mount the component in each it block. Any suggestions would be greatly appreciated!

Answer №1

I believe it's beneficial to mount the component prior to each test in order to avoid any potential side effects carrying over from previous tests.
One way to prevent code duplication is by implementing the following approach:

const expectedValues = [
        { link: '', expects: false },
        { link: 'www.google.com', expects: true },
         ....
    ]

    expectedValues.forEach(({ link, expects }) => {
        it(`should assess ${expects} for link:${link}`, () => {
            const wrapper = mount(MerchandisingArticle, {
                propsData: {
                    article: {
                       link
                    }
                }
            })

            expect(wrapper.find("a").exists()).to.equal(expects);
        })
    })

This method also allows for seamless addition of new test cases.

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

I am attempting to build a party planning website but I am encountering an issue where the output is not generating properly. Whenever I click on the submit button, the information I input

I am struggling to create a party planner website and encountering issues with the output. Whenever I click on the submit button, the form just clears out without any feedback or result. Here is what the expected output should be: Validate event date 1: ...

Replace existing styled-component CSS properties with custom ones

One of my components includes a CheckBox and Label element. I want to adjust the spacing around the label when it's used inside the CheckBox. Can this be achieved with styled()? Debugging Info The issue seems to be that the className prop is not b ...

Issue encountered when exporting with node and mongoose

After creating some schema and exporting the model, here is the code: var mongoose = require('mongoose'); var specSchema = new mongoose.Schema({ name: String, description:String }); var qualSchema = new mongoose.Schema({ name: Str ...

Welcome to the interactive homepage featuring multitouch authentication

I am looking to design a homepage that is interactive based on touch input. For instance, if the user uses 5 fingers to touch the screen, similar to the green circles in the image below, they will be redirected to a specific homepage. If they touch in a di ...

Angular 2's Conditional Validation: A Comprehensive Guide

Angular 2 offers straightforward validation, which is a great feature. However, the challenge lies in making a required field optional based on another field's selection. Below are the validation rules: this.contractsFilter = this.fb.group({ selec ...

I encountered an issue when trying to include the dotenv file, receiving the following error message: [TypeError: Network request failed]

babel.config.js File plugins: [ ["module:react-native-dotenv", { "envName": "APP_ENV", "moduleName": "@env", "path": ".env", "blocklist": null, "allowlist": null, "blacklist": null, // DEPRECATED "whitelist": ...

Having trouble figuring out the reason my JavaScript code isn't functioning properly. Any ideas?

Just starting out with javascript and running into an issue, This snippet of code seems to be working as expected: function test(args){ return "12345 - "+args; } console.log(test("678910")); However, this other piece of code is ...

Can the jQuery live function be triggered without the need for an event?

Using the live function in jQuery requires an event to trigger it. More information can be found in the official API documentation. $(".xyz").live('event', function(){ }); I am trying to make the above function run as soon as the dynamicall ...

Include a requirement within an application/ld+json formatted script

I have a task to create an application using a script in the js+json format. It is crucial to include the person schema, which signals to Google and other search engines how to effectively interpret the structure of the page and its content. My current cod ...

The innerHTML of null cannot be set in Vue JS

I am attempting to showcase my array and its modifications after applying various methods <template> <div> <div id="example"></div> <div id="example1"></div> </div> </template> <s ...

Sending back various results in a javascript function

I am attempting to correlate test scores with values from the level array in order to extract selected values into an output array. However, when I execute the following script in the Firebug console, I encounter the error message "TypeError: level is unde ...

Despite functioning properly when triggered from the debug console, the jQuery AJAX request fails to work upon page load

The issue was resolved by disabling asynchronous requests in jQuery. Here is the Javascript & AJAX request (using jQuery) code on my page: "use strict"; var hsArea, counter, hotspots, count; counter = 4; count = 0; hotspots = {}; function fetchHots ...

Utilize jQuery to style the background of the webpage, while excluding the Modal element when using Bootstrap

I'm currently working on implementing foggy.js () to create a blurred background effect for Bootstrap's Modal. While I've successfully blurred all elements in the background, the Modal Popup itself is also appearing blurry. So my question is ...

I'm curious about the reason behind the error message stating "Navbar is defined but never used" popping up while working with Vue

After importing the Navbar component from Navbar.vue, I attempted to include it in my app.vue. However, upon doing so, I encountered an error stating 'Navbar' is defined but never used. As a newcomer to Vue, I am unsure of why this issue is occur ...

When using Angular2, I have found that I am unable to extract the body data from JSONP responses. However, I have discovered that this issue

Initially, I developed the SERVER using spring-boot framework. The code for this looks like: public class App { @RequestMapping("/") @ResponseBody String home(HttpServletRequest request) { String aa=request.getParameter("callback"); System.out.pri ...

Creating a Pyraminx using triangular shapes

Attempting to create a Pyraminx, a tetrahedron made up of multiple triangles, through my coding. The approach I am taking may not be very precise. You can find my code here: https://codepen.io/jeffprod/pen/XWbBZLN. The issue I'm facing is manually in ...

In Visual Studio Code, beautification feature splits HTML attributes onto separate lines, improving readability and code organization. Unfortunately, the print width setting does not apply

I have done extensive research and tried numerous solutions, When using Angular and formatting HTML with Prettier, it appears quite messy as it wraps each attribute to a new line, for example: <button pButton class="btn" ...

Incorporating a value into vue.js will increase the existing number by the specified amount

Encountering a strange issue while setting up a pagination system. Attempting to increment the value for the next page by 1, but instead of increasing, it appears that the value is being appended. this.page = 1 <a v-if="this.total_pages > thi ...

Utilize JavaScript to assign a value to a concealed Pardot field

Recently, I've been working on setting a hidden Pardot field within an iframe. Oddly enough, when I manually input the query selector in my Chrome console, I successfully locate the element. However, when running this code snippet (embedded in the &l ...

Alert message in jQuery validation for the chosen option value

I am attempting to validate a combo box with the code provided below. Currently, I receive multiple alert messages even if one condition is true. My goal is to only display one alert message when a condition is met and highlight the other values in red. Th ...