question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Front test swal promise return with Jasmine

See original GitHub issue

Hi, first of all thxs for your work it’s great to maintain sweet alert !

I am getting an issue that I hope some of you overcame, testing the return promise of the swal() function ?

I am using swal in my component like this :

handleUpdate(newDate) {
    const swal = require('sweetalert2');
    swal({
        title: ...,
        text: ...,
        type: 'warning',
        showCancelButton: true,
        confirmButtonText: ...,
        cancelButtonText: ...
    }).then(() => {
        this.doSomething();
    }, (dismiss) => {
        if (dismiss === 'cancel' || dismiss === 'overlay' || dismiss === 'esc') {
            this.doSomethingElse();
        }
    });
}

And testing as follow :

it('With modification and click OK', fakeAsync(() => {
    // GIVEN
    comp.isDataModify = true;
    const swal = require('sweetalert2');
    spyOn(swal, 'swal').and.returnValue(Promise.resolve());
    // WHEN
    comp.handleUpdate(new Date('06/12/2017'));
    // THEN
    expect(comp.isDataModify).toBe(false);
}));

I don’t really know if I am getting the right object to spy on ? Or it’s not the right way to spy on Promises ? I got the syntax from angular documentation : https://angular.io/guide/testing#test-a-component-with-an-async-service

Txs in advance for any help on this.

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
FGAUTREAULTcommented, Jul 25, 2017

Here it is !

You need to declare SweetAlert as a service

import * as SweetAlert from 'sweetalert2';

Then use the default method to build it

SweetAlert.default({
        title: ...,
        text: ...
    })
    .then(() => { ... });

And finally with Jasmine spy on the default method to get the promise

spyOn(SweetAlert, 'default').and.callFake(function () {
    return Promise.resolve(function() {
        // Data will only be modified inside the Promise
        expect(...).toBe(...);
    });
});
0reactions
prmkishorcommented, Apr 6, 2020
deleteItem(itemId) {
    Swal({
      titleText: 'Are you sure to delete item?',
      confirmButtonText: 'Yes',
      cancelButtonText: 'No',
      showCancelButton: true
    }).then((result) => {
      if (result.value !== undefined && result.value) {
        this.itemService.deleteItem(itemId);
      }
    });
  }

can be tested as below

it('should call api to delete item on confirmation', (done) => {
    component.deleteItem('1004');
    expect(Swal.isVisible()).toBeTruthy();
    expect(Swal.getTitle().textContent).toEqual('Are you sure to delete item?');
    Swal.clickConfirm();
    spyOn(itemService, 'deleteItem').and.returnValue(Observable.of({}));
    setTimeout(() => {
      expect(itemService.deleteItem).toHaveBeenCalledWith('1004');
      done();
    });
  });

For more detail https://github.com/prmkishor/sweetAletUnitTesting/wiki/sweetAlert2-Angular-Unit-Testing

Read more comments on GitHub >

github_iconTop Results From Across the Web

Unit Testing Async Calls and Promises with Jasmine - Medium
This post will show you a simple approach to test a JavaScript service with an exported function that returns a promise. Unit testing...
Read more >
Jasmine test a promise.then function - Stack Overflow
My promise is created and returned; My loadData function is called and it will call the getData() function from the TestService; Everything inside...
Read more >
Resolving the JavaScript Promise Error "TypeError: Cannot ...
It takes two arguments, price and taxRate , calculates the amount of tax using the inputs, and is expected to return a Promise...
Read more >
Testing promises with Jasmine | TO THE NEW Blog
We have been using Jasmine to test our angular code. Recently I came across a piece of code in Javascript which included a...
Read more >
SweetAlert2 - a beautiful, responsive, customizable and ...
Swal.fire( 'Good job! ... When an alert is dismissed by the user, the Promise returned by Swal.fire() will be resolved with an object...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found