Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing Karma + Mocha tests with both dependency injection and `done`?

What's the most elegant way to write Karma unit tests in mocha that both have dependency injection and done?

Dependency injection:

describe('cows', function(){
  it('farts a lot', inject(function(cow){
    // do stuff
  }))
})

Done:

describe('cows', function(){
  it('farts a lot', function(done){
    // do stuff
  })
})

What if I want both cow and done available in my unit test? Right now, this is what I'm doing, and it's unsatisfactory.

beforeEach(inject(function(cow){
  this.cow = cow;
}))

it('farts a lot', function(done){
  this.cow // etc
})
like image 254
bioball Avatar asked Feb 26 '15 22:02

bioball


People also ask

What is difference between mocha and chai?

Mocha is a JavaScript test framework running on Node. js and in the browser. Mocha allows asynchronous testing, test coverage reports, and use of any assertion library. Chai is a BDD / TDD assertion library for NodeJS and the browser that can be delightfully paired with any javascript testing framework.

Which of the following is considered as the default test reporter of mocha?

Mocha provides a variety of interfaces for defining test suites, hooks, and individual tests, including TSS, Exports, QUnit, and Require. The default interface is behavior-driven development (BDD), which aims to help developers build software that is predictable, resilient to changes, and not error-prone.


1 Answers

You can nested function inject into test function

it("should nested inject function into test function", function(done) {
    inject(function($timeout) {

      $timeout(function() {
        expect(true).toBeTruthy();
        done();
      }, 10);

      $timeout.flush(10);

    });    
  });

inject is global function defined in ngMock module and can be used anywhere in the test.

like image 169
milanlempera Avatar answered Nov 15 '22 00:11

milanlempera