protractor icon indicating copy to clipboard operation
protractor copied to clipboard

Avoid waiting for $timeout()s ?

Open drhumlen opened this issue 13 years ago • 59 comments

In our app we display "popup" messages to our user when certain buttons are clicked. These popup messages are only visible for about 20 seconds (after which $timeout removes them).

The problem is that Protractor seems to wait until the $timeout is completed before it .findElement() and .expect()s things. However, when the $timeout is timed out, the message is gone, and the element is not found.

Any suggestion on how to bypass/solve this? (We need to assert that the correct "popup" message is displayed to the user)

Thanks

drhumlen avatar Oct 16 '13 13:10 drhumlen

You can use ptor.ignoreSynchronization, but this might cause flakiness elsewhere in your test. Alternatively, on Angular 1.2rc3, there is now an interval service, which Protractor will not wait for (see https://github.com/angular/angular.js/commit/2b5ce84fca7b41fca24707e163ec6af84bc12e83). You can set an interval that will repeat 1 time.

juliemr avatar Oct 16 '13 17:10 juliemr

Hi @drhumlen , we had the same problematic and we conclude that the popup is definitely something that should go to unit testing. So, we mocked our notification system and expect that the mock has been called (eventually with some critical informations). We also unit tested the notification to be sure that nothing breaks. Hope that help.

mackwic avatar Oct 18 '13 16:10 mackwic

$interval did the trick for us.

  $interval(function() {
    // ...
  }, duration, 1);

It now works great. But we have to be very conscientious and make sure that the popup is removed in some other way after each test (in our case, clicking the "x"-button):

  afterEach(function() {
    removeLogMessagesFromDOM();
  });

@mackwic: I suppose it's possible to test it with a unit test for many apps, but in our case, the error messages are generated by the backend, so we have to test them in the e2e.

Thanks @juliemr

drhumlen avatar Oct 23 '13 12:10 drhumlen

It seems strange that Protractor waits for $timeouts. Most of the time the user would have to work against this?

OliverJAsh avatar May 02 '14 16:05 OliverJAsh

Also faced this problem and solved it with $interval. With a little twist you can use it just like $timeout.

I wanted to test save method and verify that success notification is displayed after save. This notification was getting hidden by $timeout service. Protractor was waiting for $timeout and checking if notification is visible after it already became hidden.

Before:

$timeout(function() {
    //hide notification
}, 3000);

After:

var intervalCanceller = $interval(function() {
    //hide notification
    $interval.cancel(intervalCanceller);
}, 3000);

apuchkov avatar Jul 15 '14 19:07 apuchkov

Is this not considered a valid issue? I just ran into this myself. I don't really see that using $interval instead of $timeout is a solution, more a workaround.

redders6600 avatar Aug 01 '14 12:08 redders6600

I also can't get this to work, even if I change to $interval from $timeout.

I have a toast that disappears after a timeout. This is the code I'm using to test it:

username = element(select.model("user.username"))
password = element(select.model("user.password"))
loginButton = $('button[type=\'submit\']')
toast = $('.toaster')
# Check the toaster isn't displayed initially
expect(toast.isDisplayed()).toBe(false)  # This passes
username.sendKeys("redders")
password.sendKeys("wrongpassword")
loginButton.click()
toastMessage = $('toast-message')
# Check the toaster is now displayed
expect(toast.isDisplayed()).toBe(true)   # This passes
expect(toastMessage.getText()).toBe("Invalid password")  # This fails

The relevant markup is here (jade)

.toaster(ng-show="messages.length")
  .toast-message(ng-repeat="message in messages") {{message.body}}

The failure is that toastMessage = $('toast-message') doesn't match any elements. Is this failing because it's being called at the start, when .toast-message doesn't exist?

redders6600 avatar Aug 01 '14 12:08 redders6600

Was this issue fixed yet? Because using interval instead of timeout is hack or workarounf more than solution.

I face same issue and browser.ignoreSynchronization = true; does not help. I can replace code to $interval but e2e tests should test real code not the code adopted to them.

vytautas-pranskunas- avatar May 20 '15 12:05 vytautas-pranskunas-

@vytautas-pranskunas- sounds like there's a different issue for you if ignoreSynchronization is not working. If you can provide a reproducible example, open up a new issue.

juliemr avatar May 20 '15 16:05 juliemr

I figured out when ignoreSynchronization isnot working: I have a service which is responsible for showing error messages. Once show message stays on screen for five seconds after it fades away. This process is controlled by $timeout.

I got two scenarios - in first ignoreSynchronization works fine, in second - does not

  1. I know that messages should appear right away after user clicks button and I do expec(message).tobe(...) in this case ignoreSynchronization does the job.

  2. I know that message can appear after any amount of time (depends on server response time) and my further logic should be executed only after it appears so in this case I have to use browser.wait(by.(....).isPresent(), n) here ignoreSynchronization stops working and the flow is following (I will show browser.wait console.log output while waiting)

waits
waits
waits (element appears)
browser waits freezes for 5 seconds
after element disappears it continue
wait
wait
wait

So as you can see it never sees element present because wait freezes when in touch with $timeout

I really do not have so many time to make it reproducible in plunker but if you try to it would be great because this scenario should be quite common.

Thnaks

vytautas-pranskunas- avatar May 21 '15 06:05 vytautas-pranskunas-

You log is really not very helpful without the context of the code that created it. Could you share that?

juliemr avatar May 21 '15 06:05 juliemr

I cannot share my code because of privacy but i can show some pseudo code to get an idea (not writing html code because there is a button and ng-repeat for displaying messages)

constructor(){
$scope.$on('globalMessageAdded', () => {
            $scope.globalMessages = this.getMessages();
        });
}

callServer(){
//interval here acts like server delay
   $interval(()=> {
     $rootScope.messages.push('test messages');
      this.$rootScope.$broadcast('globalMessageAdded');
   }, 3000, 1);
}

getMessages = () => {
        var newMessages = <ISpaGlobalMessage[]>[];
        _.forEach(this.$rootScope.globalMessages, item => {
            newMessages.push(item);
//because of this timeout browser.wait stops waitng for 5 seconds
            this.$timeout(() => {
                this.remove(item);
                this.$rootScope.$broadcast('globalMessageRemoved');
            }, 5000);
        });

        return newMessages;
    }

and protractor part

element('button').click();
browser.ignoreSynchronization = true; //tried with and without it
browser.wait(() => element(by.css('.alert-success')).isPresent(), 10000000);
browser.ignoreSynchronization = false;

other code that should be executed after successful message

browser.wait never finds that element because while element is present browse.wait is not triggering checks.

vytautas-pranskunas- avatar May 21 '15 11:05 vytautas-pranskunas-

Is there any progress or thoughts on this?

vytautas-pranskunas- avatar May 27 '15 06:05 vytautas-pranskunas-

Why "browser.ignoreSynchronization = false; " cannot be set immediately after the browser.wait()?

My Code

        var el = element(by.css('.popup-title.ng-binding'));
        browser.ignoreSynchronization = true; 
        browser.wait(function (){
            return el.isPresent();
        }, 10000);
        var popupMsg = el.getText();
        expect(popupMsg).toEqual('something...');
        browser.ignoreSynchronization = false; // not work, if take out this statement, it works again

smilechun avatar Jul 23 '15 08:07 smilechun

Being bitten by the same problem. The toast module we use is a generic component for npm, so we cannot easily change it to use $interval. I also fail to see why protractor should wait for one and not the other. Ideally this would be configurable on it's own, so it doesn't affect other synchronization waits.

holm avatar Aug 20 '15 18:08 holm

We have this issue at angular-ui/bootstrap#3982 and we decided not to swap it to $interval so we come here to see if there is anything that could be done to fix the issue.

Thank you very much.

Foxandxss avatar Sep 16 '15 13:09 Foxandxss

I ran through this problem this week using a toast notification component.

Using $interval instead of $timeout is not a plausible solution. And browser.ignoreSynchronization = true does not work for me either.

Any thougths or ideas?

grvcoelho avatar Nov 15 '15 23:11 grvcoelho

Is Angular team planing to reopen this issue because more and more people run into this. It is not professional just pretend that there is no issue because you can replace $timeout with $interval because code should not be written to fit tests - tests should be written to test code.

vytautas-pranskunas- avatar Nov 16 '15 06:11 vytautas-pranskunas-

+1 We need a fix as well.

markalanevans avatar Nov 18 '15 18:11 markalanevans

Agreed. Test should be fixed. +1

zaknuces avatar Dec 17 '15 15:12 zaknuces