`AngularJs Controller Unit Testing with sweetalert Integration in Jasmine Framework`

When it comes to testing angularjs controllers with jasmine and karma, there seems to be an issue with testing codeblocks within the sweetalert function. How can I verify that the sweet function is being called from my test class in order to test whether $scope.getCategory() is executed or not? Below is a snippet of code from my controller along with a jasmine test case.

Controller:

$scope.changeCategoryStatus = function(selectedId, selectedActive, topId) {
    sweet.show({
        title : "Kategoriyi "+(!selectedActive ? 'aktif' : 'pasif')+ " hale getirmek istiyor musunuz?",
        type : "warning",
        showCancelButton : true,
        confirmButtonColor : "#DD6B55",
        confirmButtonText : "Evet, değiştir!",
        closeOnConfirm : false,
        showLoaderOnConfirm : true,
        html : false
    }, function() {
        $http({
            method : "POST",
            url : webRootUrl+"ajax/category/setActivation",
            data : {
                "id" : selectedId,
                "active" : !selectedActive
            }

        }).then(function(response) {

            //console.log(JSON.stringify(response.data))
            if(response.data.outPutDouble==-7){
                swal("Değiştirilemedi!", response.data.outPutString,"error");
            }else{
            $scope.getCategory(topId);
            swal("Bu kategorinin durumu değiştirildi","",
            "success");
            }
        }, function myError(response) {
            swal("Bu kategorinin durumu değiştirilemedi","","error");

            //console.log("***aaa" + JSON.stringify(response))
        });


    });

}

Jasmine Test Case:

  it("changeCategoryStatus success", function () {
  $scope.changeCategoryStatus(21,true,0)

  spyOn($scope,'getCategory')
  expect($scope.getCategory).toHaveBeenCalled(); });

Wondering if anyone has encountered a similar challenge before. Appreciate any assistance provided. Thank you!

Answer №1

Here's a glimpse of how I approached unit testing in my Angular 2 app

it("should remove token from localStorage", () => {
  spyOn(localStorage, 'removeItem');

  // call the deleteToken function
  comp.deleteToken();

  // introduce a slight delay for sweetAlert modal to appear
  setTimeout(() => {
    // locate and click on the specific button within the sweetAlert
    let cancelSwal: HTMLButtonElement = fixture.debugElement.query(By.css(".sa-button-container > .cancel")).nativeElement;
    cancelSwal.click();

    // verify if the callback function correctly removes "token" from localStorage
    expect(localStorage.removeItem).toHaveBeenCalledWith("token");
  }, 100);
});

It's all pretty straightforward:

  • Execute Function containing sweetAlert functionality
  • Use setTimeout to ensure visibility of swal modal
  • Identify desired DOM element via CSS selector
  • Perform necessary action (e.g., triggering a click event) to reach your callback function for testing
  • Happy Testing :)

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

Generating a compilation using ng-repeat

HTML <html lang="en" ng-app="map" xmlns="http://www.w3.org/1999/xhtml"> <body> <div ng-controller="topbarController as topbarCtrl"> <div ng-repeat="pages in topbarCtrl.topbar"> {{pages.page}} </div> &l ...

What is the best way to execute a sequence of consecutive actions in a protractor test?

To achieve logging in, verifying, and logging out with multiple users, I decided to use a loop. I came across a helpful post that suggested forcing synchronous execution. You can find it here. Below are the scripts I implemented: it('instructor se ...

Utilizing jQuery for serializing unorganized lists

I have created multiple lists within a list and I need to pass the IDs using jQuery to another PHP file (updateDB.php). I attempted to serialize the list data but was unsuccessful. I'm not certain if I have implemented it correctly, I searched extens ...

Generate a series of buttons with generic identifiers that can be easily targeted using getElementById. The IDs will be dynamically assigned

I am looking to dynamically generate unique IDs for a list of buttons, allowing me to easily target specific buttons using getElementById. Here is an example code snippet where each button has the same ID: @foreach (var cat in Model) { <div clas ...

Creating a sticky menu in a column using affix with a CSS bootstrap list-group

My goal is to develop a sticky menu utilizing CSS Bootstrap affix and the list-group menu. I have successfully implemented most of it, except for one issue when the user scrolls down. Upon scrolling down, the menu expands to fill the entire width of the ...

I'm facing an issue with binding keyboard events in Vue - any suggestions on how to resolve

Hello everyone! I'm a newcomer to the world of Vue. Recently, I encountered an issue with keyboard-event binding that has left me puzzled. Let me share the relevant code snippet below: ...other code... <template v-for="(ite ...

Turn off all page scrolling on website

Is there a way to completely eliminate scrolling on a webpage? Currently, I have implemented the following CSS: html, body { overflow:hidden; } However, this solution does not effectively disable scrolling on iOS devices. In fact, it still allows scroll ...

Is it possible for jQuery to create a popup window displaying a specific value?

Using JavaScript, I have implemented functionality to open a child window when the user clicks on a button from the parent window. The child window contains a textbox and a button. When the user clicks on the button in the child window, I want to retrieve ...

Adding an arrow to a Material UI popover similar to a Tooltip

Can an Arrow be added to the Popover similar to the one in the ToolTip? https://i.stack.imgur.com/syWfg.png https://i.stack.imgur.com/4vBpC.png Is it possible to include an Arrow in the design of the Popover? ...

Encountering a Problem with Image Rendering in Next.js

Issue: I am facing a problem while trying to display a react component using <Gallery images={images} />. The component itself is rendered, but the images from the array are not showing up initially. However, when I resize the screen by dragging the ...

Is there a way to use ajax to dynamically monitor the presence of a file in real-time?

Is there a way to automatically observe the status of a file using ajax without having to manually refresh it with a button? ...

Encountering a JavaScript issue where the error "function is undefined" appears when attempting to import the GL

I'm a beginner in Javascript and I'm currently working on a project that involves displaying a 3D model in a modal. Everything was running smoothly until I attempted to include an import statement. Once I added the line import {GLTFLoader} from & ...

Encountering a module not found error when attempting to mock components in Jest unit tests using TypeScript within a Node.js

I'm currently in the process of incorporating Jest unit testing into my TypeScript-written Node.js application. However, I've hit a snag when it comes to mocking certain elements. The specific error I'm encountering can be seen below: https ...

What is the correct way to execute a POST request?

Currently tackling a basic API project. Managed to nail the GET & DELETE requests, but the POST request is giving me a hard time. I'm almost positive it's a beginner mistake, but I can't seem to figure out the logic here. This specific file ...

What is the output of the createRange() function?

I am encountering an issue with my code that is causing the highlighted text to always appear at the end of the page when it pops up. Is there a way to make it show in the middle of the line or below the selected text instead? I have included the current ...

Showing a div based on the selected value from a dropdown menu

I am currently working on a project where I have 3 separate div elements, each with a unique ID. Depending on the selected value from a dropdown menu, I want to display one of these divs. I have created a function to handle this logic, but for some reason, ...

Concealing Social Security Numbers using AngularJS

I am currently working on masking SSN numbers using AngularJS. Expected Outcome: Before applying mask (onFocus) After applying mask (onBlur) Users are only allowed to enter numbers, and the SSN formatting is handled by filters. Below is a sample of the ...

Await the reply from Angular while using Selenium WebDriver

I am currently automating an Angular-based application using Selenium WebDriver (Java). After selecting an option from a dropdown in the Application Under Test (AUT), data is loaded onto the page through an AJAX call to a web service. However, there is no ...

Ways to access data stored in the browser's local storage

I have a unique reminder app that stores user inputs in local storage and then displays them on a different page within the app. The process of storing these values in local storage is done through this code snippet: <h2 style="text-align:center;margin ...

Setting ngModelOptions at runtime in Angular applications

Check out this code snippet: <input type="date" ng-model="arrival" ng-model-options="{timezone: 'PST'}" /> <input type="time" ng-model="arrival" ng-model-options="{timezone: 'PST'}" /> {{arrival}} It functions correctly, d ...