Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does timeout work in angular tests running in karma

I love using console log for feedback perhaps too much, and sometimes I run into code that as convention we've added $timeout in the directive/service/controller, sometimes as long as 500 ms, and now the problem is during unit test, I noticed only console.logs directly under the it constructor gets sent out to karma and output to the screen.

wrapped console logs under timeout or rather wrapped assertions under $timeout do not yield any result as if ignored, what's the solution to timeouts?

like image 451
user2167582 Avatar asked Oct 21 '13 01:10

user2167582


People also ask

What is karma in Angular testing?

Karma is a direct product of the AngularJS team from struggling to test their own framework features with existing tools. As a result of this, they made Karma and have transitioned it to Angular as the default test runner for applications created with the Angular CLI.

How do I cover setTimeout in jest?

useFakeTimers() . This is replacing the original implementation of setTimeout() and other timer functions. Timers can be restored to their normal behavior with jest.

How do I write a test case for setTimeout in jasmine?

it('expects testableVariable to become true', function(done) { testableCode(); setTimeout(function() { expect(testableVariable). toEqual(true); done(); }, 20); }); Additionally, the timer behavior could be mocked ... this method allows jasmine to step the time forward.


1 Answers

In your unit tests, you load ngMock, which overwrites the orignal $timeout with its mock. Mock $timeout doesn't work like the real JavaScript timeout. To get it to call the code that's inside it, you have to do $timeout.flush() from your unit test.

If $timeout worked like the real timeout, you would've had to write asynchronous unit-tests for all functions that use $timeout.

Here's an example of a simplified function that uses $timeout and how I test it:

gaApi.getReport = function() {   report = $q.defer()    $timeout(function() {     $http({method: 'GET', url: 'https://www.googleapis.com/analytics/v3/data/ga'})       .success(function(body) {         report.resolve(body)       })   }, 300)    return report.promise } 

A unit test:

describe('getReport', function() {   it('should return report data from Google Analytics', function() {     gaApi.getReport().then(function(body) {       expect(body.kind).toBe('analytics#gaData')     })      $timeout.flush()     $httpBackend.flush()   }) }) 
like image 150
M.K. Safi Avatar answered Sep 21 '22 02:09

M.K. Safi