Test fails in Jest - component creation test result is undefined

I am currently working on writing a Jest test to verify the creation of a component in Angular. However, when I execute the test, it returns undefined with the following message:

OrderDetailsDeliveryTabComponent › should create

expect(received).toBeTruthy()

Received: undefined

I have made sure to import all the necessary modules into the test and believe that I am correctly calling the component in the test.

This error is something new to me, as I haven't encountered it before.


import { ComponentFixture } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { OrderDetailsDeliveryTableComponent } from './order-details-delivery-table.component';
import { ConfigureFn, configureTests, MockOrderDetailsService} from '@lib/testing';
import { OrderDetailsService } from '@c3services/order-editing/order-details.service';

describe('OrderDetailsDeliveryTabComponent', () => {
  let component: OrderDetailsDeliveryTableComponent;
  let fixture: ComponentFixture<OrderDetailsDeliveryTableComponent>;

 beforeEach(async () => {
    const configure: ConfigureFn = testBed => {
    testBed.configureTestingModule({
      declarations: [OrderDetailsDeliveryTableComponent],
      providers: [{ provide: OrderDetailsService, useValue: MockOrderDetailsService }],
      schemas: [NO_ERRORS_SCHEMA]
    });
  };

const testBed = await configureTests(configure);
fixture = testBed.createComponent(OrderDetailsDeliveryTableComponent);
component = fixture.componentInstance;
component.associatedExistingDespatchData = [
  {
    item: 'CS119NVP30F',
    quantity: 1,
    despatched: '04-08-2017 05:57',
    method: 'Standard',
    trackingNumber: '',
    deliveryAddress: '14 Beetham Court',
    returnsTrackingNumber: '',
    fromLocation: 'Tackbrook Wahrehouse',
    service: 'UK',
    type: 'D',
    reference: '160501255D0001'
 }
  ];
    fixture.detectChanges();
 });
 it('should create', () => {
  expect(component).toBeTruthy();
 });
});

I am expecting the 'it' statement to evaluate as true.

The component in question looks like this:


import { AssociatedExistingDespatch } from './../../../models/OrderDetails.model';
import { Component, OnInit } from '@angular/core';
import { TableColumn, TextAlignment, DataType } from '@sharedModels/TableData.interface';
import { Subscription } from 'rxjs';
import { OrderDetailsService } from '@c3services/order-editing/order-details.service';

type AssociatedExistingDespatchData = {
deliveryAddress: string;
despatched: string;
fromLocation: string;
item: string;
quantity: number;
method: string;
reference: string;
returnsTrackingNumber: string;
service: string;
trackingNumber: string;
type: string;
};

  const emptyDespatchNote = [
 {
    deliveryAddress: '',
    despatched: '',
    fromLocation: '',
    item: '',
    quantity: null,
    method: '',
    reference: '',
    returnsTrackingNumber: '',
    service: '',
    trackingNumber: '',
    type: ''
 }
 ];

@Component({
  selector: 'order-details-delivery-table',
  templateUrl: './order-details-delivery-table.component.html',
  styleUrls: ['./order-details-delivery-table.component.css']
})
export class OrderDetailsDeliveryTableComponent implements OnInit {
associatatedExistingDespatchesSubscription: Subscription[] = [];
loadingDetails: boolean;
orderDetailsDeliveryData: AssociatedExistingDespatch[];
associatedExistingDespatchData: AssociatedExistingDespatchData[] = emptyDespatchNote;

  constructor(public orderDetailsService: OrderDetailsService) {}

  ngOnInit() {
     this.associatatedExistingDespatchesSubscription.push(
     this.orderDetailsService.orderDetails.subscribe(({ loadingDetails, data }) => {
     this.loadingDetails = loadingDetails;
       if (!loadingDetails && data) {
          this.orderDetailsDeliveryData = 
          this.orderDetailsService.getAssociatedExistingDespatches(data);
       } else {
         this.orderDetailsDeliveryData = emptyDespatchNote;
       }
     })
   );
  }

   orderDetailsDeliveryHeader: TableColumn[] = [
 { value: 'item', label: 'Item', columnWidth: '100px' },
 {
   value: 'quantity',
   label: 'Qty',
   columnWidth: '35px',
   textAlign: TextAlignment.Center
},
{
  value: 'despatched',
  label: 'Despatched',
  type: DataType.Date,
  columnWidth: '100px'
 },
 {
   value: 'method',
   label: 'Method',
   columnWidth: '95px'
 },
 { value: 'trackingNumber', label: 'Tracking No.', columnWidth: '100px' },
 {
   value: 'deliveryAddress',
   label: 'Delivery Address',
   columnWidth: '150px'
 },
 {
   value: 'returnsTrackingNumber',
   label: 'Returns Tracking No.',
   columnWidth: '130px'
  },
  { value: 'fromLocation', label: 'From Location', columnWidth: '150px' },
  { value: 'service', label: 'Service', columnWidth: '90px' },
  { value: 'type', label: 'Type', columnWidth: '40px' },
   { value: 'reference', label: 'Reference', columnWidth: '120px' }
];
}

Answer №1

Make sure to include the compileComponents() function before running your tests. Here's an example:

 beforeEach(async () => {
    const configure: ConfigureFn = testBed => {
    testBed.configureTestingModule({
      declarations: [OrderDetailsDeliveryTableComponent],
      providers: [{ provide: OrderDetailsService, useValue: 
      MockOrderDetailsService }],
      schemas: [NO_ERRORS_SCHEMA]
    }).compileComponents();
  };

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 dreaded Heroku Node.js error H10 strikes again: "Application crashed"

I recently embarked on my journey to learn NodeJS and attempted to deploy it on Heroku. However, when I used 'heroku open,' the following error log appeared: 2020-10-08T14:19:52.778660+00:00 app[web.1]: at Module.load (internal/modules/cjs/loa ...

Is there a way to locate all projects impacted by `nx`?

Currently, I am utilizing the nx tool to manage a mono repo specifically designed for typescript projects. The nx comes equipped with a command called affected, which allows me to focus solely on the changed project and any other projects that rely on it. ...

Encountered a discrepancy with npm dependencies during the update or installation process on a legacy project

I am encountering issues while attempting to run an older project. Every time I try to npm install or start the project, it throws various dependency errors, particularly related to the outdated npm version. My current node version is 16.x, whereas the pro ...

Navigating the Basics: Understanding the Four Quadrant Selection Grid in a Material UI & React Pop-Up Form

Sorry if these questions seem silly. I'm diving into React & Material-UI without a mentor to guide me, relying on documentation and tutorials. Is there a better place for quick beginner questions? Maybe a chat forum or Slack group? Not sure if Stack i ...

One typical approach in React/JavaScript for monitoring the runtime of every function within a program

Experimenting with different techniques such as performance.now() or new Date().getTime() has been done in order to monitor the processing time of every function/method. However, specifying these methods within each function for time calculation purposes h ...

Unable to utilize the three.js texture loader within a JavaScript worker environment

I'm currently experimenting with three.js to load textures. Here is the snippet from my main.js file: const worker = new Worker('../workers/worker.js', { type: 'module' }); And this is a simplified version of worker.js that ...

What is the reason behind TypeScript's lack of inference for function parameter types when they are passed to a typed function?

Check out the code snippets below: function functionA(x: string, y: number, z: SpecialType): void { } const functionWrapper: (x, y, z) => functionA(x, y, z); The parameters of functionWrapper are currently assigned the type any. Is there a way we can ...

Tips for hiding a bootstrap modal in Angular4 when it has no content

I am currently working on an Angular 4 e-commerce application. One of the requirements is to hide a bootstrap modal when there are no products in the cart. When a user selects some products, they are added to the mycart modal screen. The user also has the ...

An error has occurred during runtime due to a TypeError: The application is unable to access properties of an undefined object, specifically 'Upload'. This error has

Greetings to the amazing Stack Overflow Community! Currently, I'm developing a Next.js application that requires me to upload videos to Vimeo. To achieve this functionality, I've implemented tus-js-client for handling the uploads. However, I&apo ...

Having trouble starting the server? [Trying to launch a basic HTML application using npm install -g serve]

I am in the process of creating a PWA, but I haven't reached that stage yet. Currently, I have only created an index.html file and an empty app.js. To serve my project locally, I installed serve globally using npm install -g serve When I run the co ...

Ways to verify function arguments within an asynchronous function using Jest

I have a function that needs to be tested export const executeCommand = async ( command: string ): Promise<{ output: string; error: string }> => { let output = ""; let error = ""; const options: exec.ExecOptions = { ...

What could be causing the JQuery Post and Get methods to not respond or execute when they are invoked?

I'm currently working on a project where I need a webpage to automatically open other pages using the post method through a script, without requiring direct user input. I've tried using the JQuery post method, but haven't had any success so ...

Any idea how to dynamically insert rows and columns into a table or div element?

Can anyone assist me with this task? I have successfully completed the visual process I intended to do. How can I achieve this structure using AngularJS? The data will be stored in Json format. When the "+" symbol is clicked in a certain direction, the fi ...

What is the process for programmatically aligning two cards side by side using Material UI in React after retrieving data from an API?

I am currently working with data from an API that I need to display in the format of cards, arranged side by side. To achieve this, I have been using an array and passing the data to components programmatically. You can see the output image and my code bel ...

The authService is facing dependency resolution issues with the jwtService, causing a roadblock in the application's functionality

I'm puzzled by the error message I received: [Nest] 1276 - 25/04/2024 19:39:31 ERROR [ExceptionHandler] Nest can't resolve dependencies of the AuthService (?, JwtService). Please make sure that the argument UsersService at index [0] is availab ...

Deleting empty tags in an HTML h1 element with JavaScript

Is there a way to use JavaScript to remove empty h1 tags only? <h1>Hello World!</h1> <p>Lorem ipsum dolor sit amet</p> <h1></h1> <p>consectetur adipiscing elit.</p> <h1></h1> <p>Sed do ...

Angular's HTTP client allows developers to easily make requests to

I am struggling with grasping the concept of async angular http client. In my Java backend, I have endpoints that return data in the same format but with different meanings. To handle this, I created the following code: export class AppComponent implement ...

While conducting tests on a Vue single file component, Jest came across an unforeseen token

I need help with setting up unit tests for my Vue application that uses single file components. I've been trying to use Jest as mentioned in this guide, but encountered an error "Jest encountered an unexpected token" along with the details below: /so ...

Managing API calls through Next.js routing

Here is a next.js handler function for handling api requests on our server. I am looking for assistance on how to access a variable between request methods. Any help would be greatly appreciated. export default function handler(req, res) { if(req.met ...

Issues with manipulating state using TypeScript Discriminated Unions"Incompatibility with setState

Imagine having a unique type structure like the one shown below: export type IEntity = ({ entity: IReport setEntity: (report: IReport) => void } | { entity: ITest setEntity: (test: ITest) => void }); Both the entity and setEntity fun ...