Jest Error: Unable to access property 'foo' of an undefined value

Sharing my new QA issue to discuss my recent findings. I encountered the same error mentioned on SO, but the root cause of my problem was different. Reference: Jest: TypeError: Cannot read property of undefined

The specific error message I faced was "TypeError: Cannot read property 'apiUrl' of undefined". Despite having set esModuleInterop and allowSyntheticDefaultImports in tsconfig.json, I couldn't figure out why this error was occurring.

The error was happening within the service consumer:

import Axios from 'axios';
import config from '@/services/config.service';

const axios = Axios.create({
  baseURL: config.apiUrl || undefined,
                  ^^^^^^
  ...
});

The config services exported const config both as a named export and a default export:

export let config: AppConfig;

...

config = {...}

...

export default config;

This is how my tsconfig.json looks:

{
  "compilerOptions": {
    // Compiler options here...
  },
  "include": [
    "src/main.ts",
    "src/types/**/*",
    "src/WS_UIkit/src/types/**/*"
  ],
  "exclude": ["node_modules"]
}

Here's my jest.config.js:

module.exports = {
  preset: '@vue/cli-plugin-unit-jest/presets/typescript-and-babel',
  // testMatch: ['**/*.spec.[jt]s?(x)],'
  testMatch: ['**/*.spec.ts'],
  moduleNameMapper: {
    // Additional configurations...
  },
  transformIgnorePatterns: ['node_modules/(?!(quasar|quasar/*))'],
};

And finally, my babel configuration:

module.exports = {
  presets: ['@vue/app'],
  plugins: [
    // Babel plugins here...
  ],
};

Answer №1

One issue I faced was with exporting an uninitialized constant, specifically let config: AppConfig;. I later initialized it as config = {...}, causing it to be undefined at the time of export. Strangely, this did not cause any errors in my application - perhaps the code is executed before resolving exports. Could this behavior be different when running tests with Jest? It's puzzling why there is a discrepancy. Regardless, I have managed to resolve the problem.

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

What methods can you use to identify obsolete or inactive code within an Angular project?

For over a year, my team and I have been dedicated to developing an innovative angular application. As we engage in the ongoing process of code refactoring, our objective is to eliminate any unnecessary or obsolete code from our repository. We are seeking ...

I can't figure out why I keep receiving an "Uncaught ReferenceError: THREE is not defined" message from three.js, especially after I made sure to include a requirejs shim

My code is throwing an error that says: Uncaught ReferenceError: THREE is not defined module game { export class Add3DScene extends dragonwings.Command { @inject('ResponsiveDiv') protected _responsiveDiv: components.Res ...

Create a TypeScript function called toSafeArray that transforms any input into a properly formatted array

Is there a way to create a function that can transform any type into a safe array? toArray(null) // []: [] toArray(undefined) // []: [] toArray([]) // []: [] toArray({}) // [{}]: {}[] toArray(0) // [0]: number[] toArray('') // ['']: str ...

Ways to avoid route change triggered by an asynchronous function

Within my Next.js application, I have a function for uploading files that includes the then and catch functions. export const uploadDocument = async (url: UploadURLs, file: File) => { const formData = new FormData(); formData.append("file" ...

Resolving TS2304 error using Webpack 2 and Angular 2

I have been closely following the angular documentation regarding webpack 2 integration with angular 2. My code can be found on GitHub here, and it is configured using the webpack.dev.js setup. When attempting to run the development build using npm start ...

How to send multiple queries in one request with graphql-request while using getStaticProps?

I am currently utilizing graphCMS in combination with NextJS and have successfully implemented fetching data. However, I am facing an issue where I need to execute 2 queries on the homepage of my website - one for all posts and another for recent posts. q ...

Getting stuck in an endless loop while making a call to Axios for data fetch with React Suspense

I am currently working on fetching data using Axios and displaying it within a suspense element. I came across a tutorial that demonstrates this process: https://dev.to/darkmavis1980/a-practical-example-of-suspense-in-react-18-3lln However, I am encounter ...

Accessing external data in Angular outside of a subscription method for an observable

I am struggling to access data outside of my method using .subscribe This is the Service code that is functioning correctly: getSessionTracker(): Observable<ISessionTracker[]> { return this.http.get(this._url) .map((res: Response) => ...

Creating a HTML element that functions as a text input using a div

I am encountering an issue with using a div as text input where the cursor flashes at the beginning of the string on a second attempt to edit the field. However, during the initial attempt, it does allow me to type from left to right. Another problem I am ...

Encountering an issue with React Hooks Form and MUI DatePicker when trying to select a different date causing an

I have been attempting to wrap the MUI date picker into a custom component. This is what I have done: export interface IMessage { id?: string | undefined; title?: string | undefined; content?: string | undefined; date?: Date | undefined; } ...

How can I group every 3 elements in a div using React?

I've been trying to achieve a layout where there are 3 red divs enclosed within a blue div. However, despite following the suggested method from https://stackoverflow.com/questions/63695426/react-wrap-every-3-components-into-a-div, I'm unable to ...

"Despite the inability to use the clear input field function in Angular, users can still effectively clear

Why does the X button not clear and refresh the field when clicked, but using backspace does? I want it to clear when the X button is clicked. <mat-form-field appearance="standard" fxFill> <mat-label style="font-size: 12 ...

a callback may seem like it's not a function, but in reality, it is

This question might seem simple, but I'm struggling to grasp the concept of callbacks, especially in NodeJS. My issue arises when trying to retrieve data from MySQL, something that is usually straightforward in most programming languages: In my rout ...

Tips for implementing a cascading dropdown feature in Angular 7 Reactive Formarray: Ensuring saved data loads correctly in the UI form

I recently found a helpful guide on stackoverflow related to creating cascading dropdowns in an Angular reactive FormArray, you can check it out here After following the instructions, I managed to achieve my desired outcome. However, I now face a new chal ...

BotFramework: Transferring information between a skill and a Virtual Assistant

Currently, I am faced with the challenge of trying to trigger Skill B from Skill A within a Virtual Assistant without any additional user input. This process requires passing data from Skill A to the Virtual Assistant and then from the Virtual Assistant to ...

Ways to prevent Deno Workers from using cached source code

Good day, I am currently working on building a custom javascript code execution platform using Deno Workers. Additionally, I have implemented an Oak web server to manage requests for script modifications and their compilation and execution. An issue arise ...

Error: Unable to access $rootScope in the http interceptor response function

I have set up an interceptor to display an ajax spinner while loading. interface IInterceptorScope extends angular.IRootScopeService { loading: number; } export class Interceptor { public static Factory($q: angular.IQService, $ro ...

Swap out a specific object within an observable array by comparing object properties

Currently, I am retrieving an observable array of custom IPix objects (Observable<IPix[]>) from a database using an API. After that, I update a record in the database by sending an edited version of the IPix object back to the API through a PUT reque ...

I encountered a mysterious Debug entry in my package.json within Visual Studio that seems impossible to remove

I found an unexpected Debug statement in my package.json file and I'm unsure of how it appeared there. I have no clue how to remove it either. https://i.stack.imgur.com/P7RFn.png Any ideas on how I can eliminate it from the file? ...

What could be causing the problem between typescript and Prisma ORM as I attempt to locate a distinct item?

I'm encountering a problem with using the prisma .findUnique() function. Even though my code doesn't display any compilation errors, attempting to access a product page triggers a runtime error. PrismaClientValidationError: Invalid `prisma.produ ...