r/angularjs • • Jan 01 '16

Not testing your Angular app? Here's how to start. (Karma setup w/ video)

https://daveceddia.com/testing-angular-part-1-karma-setup/
45 Upvotes

8 comments sorted by

2

u/[deleted] Jan 02 '16

I really find the extra layering of using angular's injection pipeline annoying. I tend to extract out the functionality and leave the testing angular functionality to angular. In that example I would just export the actual function definition of the factory and test that separately. If there is call for some angular testing such as testing watchers I'll do that as a seperate context in the suite. I try my best to test plain javascript constructs like functions/objects/classes.

1

u/simcptr Jan 02 '16

The boilerplate kinda sucks, and it does feel a little like testing Angular sometimes. What do you do when testing functions that themselves require angular's injector though? Don't you end up manually mocking those out? Or have you avoided that by the way you structure your code?

I'd be interested in seeing examples of you have any, it seems like that style could turn out cleaner.

1

u/[deleted] Jan 02 '16

A bit contrived but this is an example of what I'd do. https://jsfiddle.net/82z7d735/

The actual factory would be exported seperately, and wherever you initialize your app from you'd import the modules and use them, clears some clutter of including your angular module definitions with the code under test. In the test you just have to worry about creating the appropriate mocks. Ususally easy with a nice mock/spy framework. And test the module.

Could you give me an example of a scenario where a function would require angulars injector. Since angular requires you to even inject that it would be easy enough to create a stub of that.

1

u/[deleted] Jan 03 '16

that's a real clean example, i like that. What about directives though? Do you have a nice way to test those?

1

u/[deleted] Jan 03 '16

So this I'm sure can be countered but my philosophy is that if I need to test something heavily UI centric, I'd leave it to UI tests/QE and such. I recently wrote a UI Centric directive and did something similar to my example. The functionality, mostly static with no global dependencies, would be in it's own object similar to this. The directive definition would then have to be a bit larger, with the UI parts and calls to the core functionality object for the directive. I would test that core seperately and leave the UI Centric cases to another tool or QE if at work.

1

u/[deleted] Jan 03 '16

yeah that's pretty much what i do. I tried unit testing directives and it's such a pain in the ass that I just let the e2e tests cover them implicitly.

4

u/[deleted] Jan 01 '16

[removed] — view removed comment

4

u/simcptr Jan 01 '16

That's a good idea. I tried to focus on the bare essentials to make it as simple as possible, but coverage reports are a great addition once you get rolling.