简体   繁体   English

Angular中的单元测试

[英]Unit testing in Angular

As I understand Scenario-runner is deprecated. 据我了解,不建议使用Scenario-runner。 So now you will run your unit tests in Karma and e2e test in Protractor. 因此,现在您将在Karma中运行单元测试,并在Protractor中运行e2e测试。

For me it feels wrong to start a browser(karma) for running you unit tests. 对我来说,启动用于运行单元测试的浏览器(karma)感觉不对。 Are my assumptions correct? 我的假设正确吗? How do you test your Angular applications? 您如何测试Angular应用程序?

A fairly well practised standard when it come to testing angular is to use phantomjs a headless browser to do the unit testing. 在测试角度时,一个相当好的实践标准是使用phantomjs无头浏览器进行单元测试。 Whatever way you look at it you need a javascript engine up and running before you can test. 无论您以哪种方式查看它,都需要启动并运行JavaScript引擎,然后才能进行测试。 However, using a headless browser is a lot quicker as there is no UI. 但是,由于没有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. 我使用Karma,chai和sinon(用于模拟)-我的开发工作流程使用phantomjs,然后我的CI和发布版本使用实际的浏览器IE,Chrome等运行CI构建时也使用BrowserStack。

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. 您可能需要查看grunt / gulp才能实际管理测试过程。

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. 不同的浏览器具有不同的DOM实现,JavaScript版本和功能等。

For example, if you were to run the following code in Chrome or PhantomJS it would work fine, but in IE8 it would fail: 例如,如果您要在Chrome或PhantomJS中运行以下代码,则可以正常运行,但在IE8中,它将失败:

var arr = [1, 2, 3]

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

forEach isn't available in IE8, but it is in Chrome. forEach在IE8中不可用,但在Chrome中可用。 A Unit test that ran the code against IE8 would have caught that, a unit test against PhantomJS would not have caught that. 针对IE8运行代码的单元测试可能会发现这一点,而针对PhantomJS的单元测试则不会发现这一点。

... 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) ...因此,如果您想在开发周期中运行诸如PhantomJS之类的“无头”工具,那很好,但是请务必确保正在测试构建时关心的所有浏览器(希望使用CI)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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