Determine if two arrays are equal using Jest

I have a method in the test.ts file:

public async listComponentsDiffer(lastTag: string, workDir: string): Promise<any[]> 

This method returns an array with data like this:

[{ components: "toto", newVersion: "2", oldVersion: "1" }]

I am attempting to use Jest to test this method:

test("correct array format", () => {
    // Given
    const lastag = "";
    const workDir = ".";

    // When
    const result = ComponentsService.listComponentsDiffer(lastag, workDir);

    // Then
    const expected = [{ components: "toto", newVersion: "2", oldVersion: "1" }];
    expect(result).toBe(expected);
});

However, I am encountering the following error:

TypeError: test_1.test.listComponentsDiffer is not a function in Jest

How can I properly run my test?

Answer №1

  1. Make sure to call this method from an instance of the class as it is not a static method.

  2. If you are using async/await syntax, don't forget to include async/await in your test case as well.

  3. Instead of using .toBe, consider using .toEqual for proper comparison.

Use .toEqual for deep equality comparison of object instances.

For example:

test.ts:

export class ComponentsService {
  public async listComponentsDifferent(lastTag: string, workDir: string): Promise<any[]> {
    return [{ components: 'toto', newVersion: '2', oldVersion: '1' }];
  }
}

test.test.ts:

import { ComponentsService } from './test';

describe('12345678', () => {
  test('checking correct array form', async () => {
    const lastag = '';
    const workDir = '.';
    const instance = new ComponentsService();

    const result = await instance.listComponentsDifferent(lastag, workDir);

    const expected = [{ components: 'toto', newVersion: '2', oldVersion: '1' }];
    expect(result).toEqual(expected);
  });
});

Results of unit tests:

 PASS  stackoverflow/12345678/test.test.ts (7.968s)
  12345678
    ✓ checking correct array form (6ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.014s

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

Customize the dynamic options for selecting with Bootstrap

I have been experimenting with the bootstrap select plugin and have run into an issue while trying to dynamically add options using Javascript. Unfortunately, the list always appears empty. Interestingly, when I revert back to using a conventional HTML sel ...

Angular release 6: A guide on truncating text by words rather than characters

I'm currently enhancing a truncate pipe in Angular that is supposed to cut off text after 35 words, but instead it's trimming down to 35 characters... Here is the HTML code: <p *ngIf="item.description.length > 0"><span class="body-1 ...

Prioritize establishing the connection before guiding the user to a new destination

I have a brilliant idea for creating something amazing, but I'm uncertain if it's feasible. Here is a basic example of an ajax function that could potentially establish a connection with a server... function getFakePage(userId) { var ajaxObj ...

Execute local server's unit tests using a Gulp task

I am currently faced with the challenge of running automated unit tests in the terminal for a library application that utilizes the History API internally. To achieve this, I am utilizing Babel to transpile and consolidate my Mocha/Chai/Sinon unit tests in ...

Ways to clear dropdown selection in Vue based on a specific condition?

I am currently developing a dropdown menu for selecting visit status options, which include "pending," "canceled," "rejected," and "approved." In the case of an approved visit status, I would like the dropdown selection to only display the options for "can ...

What are the limitations of using a JS file within an Angular application?

I am struggling to integrate some js methods from a file into an angular application. Unfortunately, the browser is unable to recognize the js file. I have tried following the guidelines in this SO post, but the browser still cannot locate the file in the ...

Another return payload failing to retrieve the return value

I'm currently facing an issue where a function that should return a value is not being passed on to another function. Below is the code snippet in question: public _getProfileToUpdate() { return { corporateId: this.storeService.setStoreData().p ...

The fetch method in Express.js resulted in an error 404 because the requested URL could not be found

Having trouble locating the URL when trying to fetch data for a POST request. I want to mention that my code is written in node.js and express.js. The error message being generated: const form = document.querySelector('form'); form.addEventList ...

Running multiple npm scripts on both Unix and Windows systems can be achieved by using the "npm

Is there a way for me to execute multiple npm scripts synchronously, one after another? Below are the npm scripts I have in my project, which includes both bower and npm packages: { "scripts": { "installnpm": "npm i", "installbower": "bower i", ...

Is there a way to identify the element causing an error in promise.map and then either log it to the console or skip it using code?

When running the code provided below, I encounter a 500 error for certain URLs in my list due to the structure of the page. The error occurs specifically on the line .map((htmlOnePage, index) => when some URLs lead to invalid pages, causing the prog ...

Switch the background color alternately from red to green every second

Need help with a webpage that changes the background color every second using JavaScript. The issue lies in figuring out how to correctly change the variable within the function. Here's an example of the code: <!DOCTYPE html> <html> ...

Creating a HTML and JavaScript carousel without relying on the animate function

I am currently facing some challenges with building a custom slider. While it moves forward smoothly using CSS animation, I'm struggling to implement a backward motion with an animation. It seems like I need to loop through the slides and try a differ ...

Designing the Firebase Structure of an Angular Application

What is the best way to structure Firestore and Angular for efficient querying? When using a JSON Cloud Firestore database, one of the challenges is inserting people and relating them to users. To optimize query speed and efficiency, it is important to c ...

Creating a module within a component in angular - step by step guide

I am interested in dynamically creating a component inside another component. This will allow me to pass my dynamic HTML template directly to the decorator like this: //code /** * @param template is the HTML template * @param container is @ViewChild(& ...

Delaying Variable Assignment in Node.js until Callback Function Completes

I am currently working with Node.js, Express, MongoDB, and Mongoose in my project. One specific task involves fetching the largest id number of a document from the MongoDB database and passing it back to the program. To better organize my code, I moved thi ...

Any ideas for handling ProtractorJS timeouts while clicking an element?

The Issue at Hand I am currently facing a challenge with clicking a straightforward 'New Booking' button in my Angular 5 Material 2 Application. The code snippet for the button is as follows: <button _ngcontent-c9="" class="mat-menu-item" ma ...

How to make multiple requests to populate a single object in MongoDB

I am in the process of developing a forum and I need to find out the number of messages in each topic. In my GetListTopic method, I retrieve the list of topics and then I query the forum_message table to count the messages for each topic in my list: db. ...

Prevent form submission from refreshing the page by using jQuery and ajax

I'm looking to submit a form without refreshing the page, but my current script isn't working as expected: $('#formId').submit(function(e){ $.ajax({ type: "POST", url: 'serverSide.php', data: $(&ap ...

Testing a Vue.js/Node.js application using Websockets

I'm working on a Vue project (version 3.0.3) integrated with a Node.js server. Can you provide guidance on how to conduct unit testing for this setup? The application is a game that relies on web-sockets for communication. ...

Displaying each character of text individually with jQuery

I am trying to display the text within a ul tag one by one when hovering over some text. However, I am encountering an error. How can I resolve this issue? You can view the code for mouseover functionality by hovering over the "hover here hover again" lin ...