Issue encountered during rendering: "TypeError: Attempting to access property '_t' of an undefined object" while running a Unit Test using Jest

I spent hours troubleshooting a unit test for my Vue.js component, but no matter how much I searched the internet, I kept encountering this error:

console.error node_modules/vue/dist/vue.runtime.common.dev.js:1884
TypeError: Cannot read property '_t' of undefined
at Proxy.Vue.$t ([...]\node_modules\vue-i18n\dist\vue-i18n.common.js:194:17)
at Proxy.render ([...]\src\components\Foo.vue:186:175)
at [...]

In Foo.vue, I utilize $t provided by the vue-i18n plugin like this:

<template>
  <b-form-group :label="$t('foo.label')">
    [...]
  </b-form-group>
</template>

This is what my Foo.spec.ts file looks like:

import { createLocalVue, shallowMount, mount } from "@vue/test-utils";
import Foo from "@/components/Foo.vue";
import { i18n } from "@/i18n";

describe("Foo", () => {
  const localVue = createLocalVue() as any;
  localVue.use(i18n);
  
  const wrapper = mount(Foo, { localVue } ) as any;

  describe("removeLabel", () => {  
    it("should remove label", async () => {
      // Arrange
      const index = 1;

      // Act
      wrapper.vm.removeLabel(index);

      // Assert
      expect(wrapper.isVueInstance()).toBeTruthy();
      // [more expectations... ]
    });
  });
});

Despite checking numerous similar Stack Overflow issues related to this error message, none of them seem to apply to my unit test scenario.
Following Vue.js documentation, I attempted to pass a mock into the mount function for _t, but unfortunately, it did not resolve the issue:

const $mocks = { $t: () => {} };
const wrapper = mount(Foo, { localVue, mocks: { $mocks } }) as any;

If anyone has any insights or suggestions to offer, they would be greatly appreciated.

Answer №1

After researching Github issues related to the error at hand, I stumbled upon this insightful comment made by cesalberca:

"This solution is effective as long as it remains shallow. Deeper nesting of components utilizing translations will cause test failures [...]"

By replacing mount with shallowMount, I successfully resolved the issue:

// const wrapper = mount(Foo, { localVue, mocks: { $t: () => {} } }) as any;

const wrapper = shallowMount(Foo, { localVue, mocks: { $t: () => {} } }) as any;

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

Guide to changing the active class in a nested component within VueJS

I have a tree component similar to the default Vue tree view example. I am trying to toggle the active class on click of a tree item, but every element ends up having the active class. I'm not sure where I went wrong. The non-recursive component works ...

Error encountered with TypeScript template literals strings type

There's a new feature in the latest version of Typescript that allows the use of template literal strings as types, like this: type Hey = 'Hey'; type HeyThere = `${Hey} There`; It works perfectly in the Typescript playground with version 4 ...

Setting up Auth0 redirect URL for Vue/Quasar and Capacitor hybrid application

I'm facing some challenges setting up Auth0 for my Quasar app with Capacitor integration. Although auth0-lock works properly, I am unsure how to handle callback URLs when the app is running on a device with Capacitor. For instance, providing a callbac ...

Generating dynamic content

I require assistance with a programming issue. I am working with two separate components: Stage and Executor. Within the Stage component, I am attempting to create new elements based on input parameters, while in the Executor component, I set these paramet ...

Challenges in designing components in Angular 2.0 and beyond

Issue at hand - There are two input controls on the same page, each belonging to separate components. When a value is entered into the first input box, it calculates the square value and updates the second input control accordingly. Conversely, if the v ...

How can I confirm if a class is an instance of a function-defined class?

I have been attempting to export a class that is defined within a function. In my attempts, I decided to declare the class export in the following way: export declare class GameCameraComponent extends GameObject { isMainCamera: boolean; } export abstra ...

What are the steps for implementing a heatmap in Vue Highcharts?

Struggling with error 17 while attempting to use a heatmap chart type in vue-highcharts. I've searched online and it appears that importing and correctly using it may solve the issue. Can someone guide me through this process as there seems to be no d ...

Unable to attach 'gridOptions' as it is not a recognized attribute of 'ag-grid-angular' component (Angular4)

I am facing an issue with my HTML code and Angular components: <ag-grid-angular [gridOptions]="gridOptions"></ag-grid-angular> My component code is as follows: import {GridOptions} from 'ag-grid'; ... export class SampleComponent ...

In Angular, make a call to a second API if the first API call times out after a specified period

In the event that my API does not return data within 5 seconds, I need to call a different one. Attempted implementation: this.service.returnData1(param1, param2) .pipe(timeout(5000), finalize(() => this.callSecondApi())) .subscribe( data => { ...

Having trouble getting images to display in Vue markdown?

I am currently utilizing the vue-markdown package for rendering markdown content. The package works fine except for images, which do not display as expected. Interestingly, when using an img element with the correct file path, the image shows up without an ...

What is the process for unit testing the 'navigate' function in Angular that includes query parameters?

Below is the code snippet from my component: editThis(id) { this.router.navigate(['/categories/edit'], { queryParams: { id: id } }); } The following represents my unit test-case: fit('should call navigate with correct parameters&ap ...

Error: inability to execute performanceMeasurement.startMeasurement due to its absence in the function definition

An error occurred when attempting to login using @azure/msal-react in Next 13. Upon checking the error log, it was found that the error originated from the core library @azure/msal-react. Even after trying with a login popup, the error persisted. In my co ...

Exploring TypeScript: Understanding how to define Object types with variable properties names

Having an issue with a React + TypeScript challenge that isn't causing my app to crash, but I still want to resolve this lingering doubt! It's more of a query than a problem! My goal is to set the property names of an object dynamically using va ...

Vue.js mobile app may show a loaded DOM that remains invisible until the screen is tapped

I am facing a peculiar issue that has me stumped. On my mobile device, my page initially loads like this homepage However, once I tap the screen, all the components suddenly appear. Is there a way to simulate a click on my mobile? I'm struggling to u ...

Plugin for managing network connectivity in Ionic framework

In order to check if internet and id connection are available, I need to make a server request. I have implemented the Ionic Native Network Plugin following their official documentation. Here is my code snippet: import { Component } from '@angular/c ...

The Vuetify v-spacer does not seem to be working as intended

When using the <v-dialog> modal, I am attempting to stick one block to the bottom of the <v-col> block by utilizing the <v-spacer> component, but it does not seem to have any effect. What could be causing this issue? You can view an exam ...

Why is it that eslint is unable to detect interfaces (specified in *.d.ts files) within *.vue files?

env.d.ts: declare interface Operators { plus?: '+' minus?: '-' multiple?: '*' division?: '/' } declare interface Rule { digits: number operators: operator[] calcTimes: number } type operator = '+ ...

Creating a canvas that adjusts proportionally to different screen sizes

Currently, I am developing a pong game using Angular for the frontend, and the game is displayed inside an HTML canvas. Check out the HTML code below: <div style="height: 70%; width: 70%;" align="center"> <canvas id=&q ...

Error TS2339: The member 'sort' is not found in the type 'BehaviorSubject<AbstractControl[]>'

Looking to create a dynamic table using Angular material where I can dynamically add or remove data. As a newcomer to Angular, I found the following StackBlitz helpful in setting up the table: https://stackblitz.com/edit/angular-material-editable-table-fa ...

Creating a Typescript interface for a anonymous function being passed into a React component

I have been exploring the use of Typescript in conjunction with React functional components, particularly when utilizing a Bootstrap modal component. I encountered some confusion regarding how to properly define the Typescript interface for the component w ...