简体   繁体   中英

Unit testing in Angular

As I understand Scenario-runner is deprecated. So now you will run your unit tests in Karma and e2e test in Protractor.

For me it feels wrong to start a browser(karma) for running you unit tests. Are my assumptions correct? How do you test your Angular applications?

A fairly well practised standard when it come to testing angular is to use phantomjs a headless browser to do the unit testing. Whatever way you look at it you need a javascript engine up and running before you can test. However, using a headless browser is a lot quicker as there is no UI.

I use Karma, chai and sinon (for mocking) - my dev workflow uses phantomjs and then my CI and release builds use actual browsers IE, Chrome etc I also use BrowserStack when CI builds run.

You can see an example of the tests and the karma config here

You will probably want to look at grunt / gulp to actually manage the process of testing.

Anything you were after in particular around testing?

If you want to know how your app will behave in different browsers, you'll want to run it in those browsers. Different browsers have different DOM implementations, JavaScript versions and features, etc.

For example, if you were to run the following code in Chrome or PhantomJS it would work fine, but in IE8 it would fail:

var arr = [1, 2, 3]

arr.forEach(function(item) {
  console.log(item);
});

forEach isn't available in IE8, but it is in Chrome. A Unit test that ran the code against IE8 would have caught that, a unit test against PhantomJS would not have caught that.

... so if you want to run something "headless" like PhantomJS for your development cycle, that's fine, but be very sure you're testing all of the browsers you care about when you build (Hopefully with CI)

我真的不喜欢每次运行Karma时都启动Chrome,因此我改用了PhantomJS,它“安静”地工作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM