how to use $timeout in unit test

5,227 views
Skip to first unread message

Dan Doyon

unread,
Jul 12, 2012, 1:01:22 PM7/12/12
to ang...@googlegroups.com
I've hunted high and low, but am unable to find sample code for unit testing when you need $timeout. We have angular-mock library defined in the test-config. Cd someone provide example?

thx


--dan

Pawel Kozlowski

unread,
Jul 12, 2012, 1:23:27 PM7/12/12
to ang...@googlegroups.com
Hi Dan!

On Thu, Jul 12, 2012 at 7:01 PM, Dan Doyon <dand...@yahoo.com> wrote:
> I've hunted high and low, but am unable to find sample code for unit testing when you need $timeout. We have angular-mock library defined in the test-config. Cd someone provide example?

Here you go: http://jsfiddle.net/pkozlowski_opensource/Qktpe/1/

Ioc + Jasmine is simply awesome!

Cheers,
Pawel

Dan Doyon

unread,
Jul 12, 2012, 2:21:03 PM7/12/12
to ang...@googlegroups.com
Thanks for quick response Pawel, I was very close to this. I'm getting a message about $timeout being non-existent, could be a typo somewhere. Just having your working example will be of great help.

--dan
> --
> You received this message because you are subscribed to the Google Groups "AngularJS" group.
> To post to this group, send email to ang...@googlegroups.com.
> To unsubscribe from this group, send email to angular+u...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/angular?hl=en.
>

Dan Doyon

unread,
Jul 12, 2012, 4:33:43 PM7/12/12
to ang...@googlegroups.com
Hmmm, not having luck, I'm getting message about $timeout note being defined.

angular-mocks is loading up

Here is debug for loading modules, we're using testacular

debug (config): Resolved file /Applications/MAMP/htdocs/angular-ui/test/lib/angular-1.0.1/angular.js
debug (config): Resolved file /Applications/MAMP/htdocs/angular-ui/test/lib/angular-1.0.1/angular-mocks.js

Here is test

  describe('model change', function() {
    it('should open modal',  inject(function($timeout) {
      scope.$apply(function() {
        scope.modalShown = true;
      });
      $timeout.flush();
      expect(elm.hasClass('in')).toBe(true);
    }));

Here is error

 ReferenceError: $timeout is not defined
            at HTMLDivElement.<anonymous> (/Applications/MAMP/htdocs/angular-ui/modules/directives/modal/src/modal.js:15:9)

Dan Doyon

unread,
Jul 12, 2012, 9:14:17 PM7/12/12
to ang...@googlegroups.com
that was the secret sauce. One thing that tripped me up is when I declared var $timeout at top of the test suite, it choked. 

thank you, thank you

--dan


On Jul 12, 2012, at 4:26 PM, Ricardo Bin wrote:

You can get $timeout using $injector

inject(function($injector) {
var $timeout = $injector.get('$timeout');
//...
$timeout.flush();
})
To view this discussion on the web visit https://groups.google.com/d/msg/angular/-/RXwXdLSw_hwJ.
Reply all
Reply to author
Forward
0 new messages