Employ Jest when creating a function in TypeScript

As a newcomer to jest, I am diving into testing with this new library. Before me lies the challenge of testing the following method:

public static getProjectBranch(toto: any): string {
    if ("branch" in toto) {
        return toto.branch;
    } else {
        return "master";
    }
}

This method is nestled inside a class named totoService.ts

In my totoService.spec.ts file, here is what I have done so far :

describe("Test get Project Branch", () => {
test("branch is in component", () => expect(getProjectBranch()).toBe(""));
});

I'm curious to know if my testing approach is on point or not? Additionally, I'm seeking guidance on how to correctly import the getProjectBranch method in the file.

Answer №1

If your method getProjectBranch is static, you can simply implement it as shown below:

describe("TotoService",() => {
  describe('getProjectBranch', () => {
    test("branch is in component",() => {
      const toto = {branch:''}; //create your test object here
      expect(totoService.getProjectBranch(toto)).toEqual(''); //call the static method of TotoService
    })
  })
})

To call non-static methods, you must create an instance of totoService using the beforeEach function before each test:

describe("TotoService",() => {

  let totoService;

  beforeEach(() => {
    totoService = new TotoService();
  })

  describe('getProjectBranch', () => {
    test("branch is in component",() => {
      const toto = {branch:''};
      expect(totoService.getProjectBranch(toto)).toEqual('');
    })
  })
})

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

Tips for initiating and terminating the evaluation of a condition at regular intervals using JavaScript

I'm currently working on a JavaScript application where I need to achieve the following: Periodically check every 5 seconds to see if there is an element with the 'video' tag on the page. Once an element with the 'video' tag ...

Flatten Angular Promises in a Synchronous Manner

Is there a way to run a series of promises synchronously, ensuring that the second promise is not executed until the first one is completed? I need to load data in chunks of 10 clients each and display the first N clients while the rest are loading. I wan ...

Maximizing the efficiency of rendering components in Ember JS

I have a situation where I need to render thousands of components inside a wrapper component, but currently only around 300 components are being rendered due to performance issues. How can I achieve this without any rendering delays or performance proble ...

I am facing an issue where there is no output displayed in the body when making a request call from the VueJS Front

I'm currently working on a VueJS web application that interacts with a C# WebAPI in the background. I have successfully created an endpoint, but I am facing an issue where the body of the response is always null. While debugging in the network tab, I ...

Updating the Background Color of a Selected Checkbox in HTML

I have a straightforward question that I've been struggling to find a simple answer for. Can anyone help me with this? Here's the checkbox code I'm working with: <input type="checkbox"> All I want to do is change the backgr ...

Optimizing performance with frontend caching using requireJS in a Node.js environment

Currently, I am in the process of incorporating fingerprinting into my node.js server. To achieve this, I am utilizing requirejs and my main page is loading scripts in the following manner: <script src="/public/assets2/scripts/lib/requirejs/require.js" ...

Unable to successfully upload file using AJAX & PHP - the $_FILES array remains empty

I have scoured numerous online forums and Stack Overflow threads in search of a solution to my problem, but I am still unable to make it work. Despite having 5 years of experience working with jQuery and PHP, this is my first time delving into AJAX. Curre ...

Surprising Outcome when Dealing with Instance Type - Allowing extra properties that are not explicitly stated in the type

I've come across an issue with the InstanceType Utility Type. I am trying to create a function that takes a class constructor and an instance of that class. For instance: export type Class<T=any> = { new(...args: any[]): T; }; function acceptC ...

Limited to IE6 and 7 - Issue with CSS/jQuery animation

After putting in 8 hours of non-stop work, I'm feeling pretty drained and need some assistance with fixing a bug that's specific to IE6/7. Any jQuery/CSS experts out there willing to lend a hand? To check out the issue, please visit this link us ...

What could be causing the hover style to not take effect on the leaf nodes in jQuery Treeview?

Upon reviewing Sample 1 on this specific page, you may notice that the text turns red when hovering over the folder entries, but not for the leaf entries. My goal is to have the styling for the leaf entries mimic the behavior of the folder entries. Each b ...

Counting selected files can be done by following these steps

My form includes a simple input field like so: <input id="my_id" multiple="true" type="file" name="image_name[]" /> I need help with the following questions: What is the best way to calculate the number of selected files using jQuery or pure Java ...

Is there a way to reach my vue instance while inside a v-for iteration?

When using a v-for loop, I encounter an error: <div v-for="index in 6" :key="index"> <div class="card h-100" style="margin-top: 200px;"> <a href="#"> <img ...

Having trouble loading a JavaScript file in Nuxt? Experiencing some unexpected behavior?

I have a template with HTML/CSS/JS files that I want to make dynamic using Nuxt.js. I started by copying the index.html to the Nuxt project and transferring all the necessary data to nuxt.config.js, including CSS and JS files. The page renders without erro ...

Storing user input as an object key in typescript: A comprehensive guide

When delving into Firestore for the first time, I quickly learned that the recommended modeling approach looks something like this: check out the model here members { id: xyz { name: Jones; ...

Using TypeScript to Declare Third Party Modules in Quasar

I'm currently trying to integrate Dropzone-vue into my Quasar project. However, I've encountered an issue as I can't directly install and declare it in a main.js file due to the lack of one in Quasar's structure. Additionally, an error ...

Issues with Toggling Visibility in HTML, CSS, and Javascript

Currently, I am working on a website and following a tutorial called "Creating Slideshow using HTML, CSS, and Javascript" by W3Schools. In the project, I want to hide the thumbnail images located at the bottom and the navigation arrows initially and have t ...

The value of a variable decreases upon being utilized in an Ajax API call

My tempid variable seems to lose some of its values when passed into the second API call. Despite logging the variable to console (console.log(tempid)) where it appears fine, once placed in the API call it only retains some of its value. I'm uncertain ...

Unexpected Results from WordPress Ajax Request

Currently, I am utilizing the snippets plugin in conjunction with Elementor. To implement an ajax function as a snippet, I have set it up like so: add_action( 'wp_ajax_get_slug_from_id', 'get_slug_from_id' ); add_action( 'wp_ajax_n ...

modifying input field with radio button selection in Jquery

Is there a way to set the input field to have a default value and then change it, or disable it with a different value? $("#tax").value(19).prop("disabled",false); $("#tax").value(0).prop("disabled",true); <script src="https://ajax.googleapis.com/aj ...

Adding a Data Attribute to Bootstrap 5 Popovers

I'm facing an issue with a group of buttons that have a data-attribute I want to include in the popover they trigger. HTML: <button type="button" class="btn btn-yellow btn-deleteTeacher" data-bs-toggle="popover" role= ...