简体   繁体   中英

How can I unit test in JavaScript? (the right way)

I have been trying out different JavaScript unit testing libraries, but I still don't know what's the right way of doing this.

Is there a consensus on this subject?

For instance, I tried to write some tests for a modal window library with QUnit (the unit testing library used by jQuery), but it has to be run in the browser, and it doesn't hide the effects I'm testing, or other annoying things like the alerts (I don't even know if that is possible in JavaScript). In a server-side language, any output generated by a test suite would be sent to a buffer and get discarded after each test.

If alerts, DOM manipulations, and that kind of things are not encapsulable in JavaScript unit testing, is writing tests worth the effort in this language?

Testing frontend code (HTML, CSS, and JavaScript) is not an easy task mostly thanks to cross-browser issues which require visual testing eg. making sure an element is correctly positioned in all browsers.

In order to test your JavaScript code you need to write it in a "testable" way. I personally found this blogpost very helpful: Writing Testable JavaScript

As for the actual testing, try to combine QUnit (which you are already using) with http://funcunit.com/ . FuncUnit lets you open a HTML page and run tests on its DOM. There's an example on the home showing how it's done.

If you are really annoyed by the DOM alterations and other effects (alert and prompt) you could use mocking and spying to ensure that those alterations are intended.

See Jasmine BDD that includes mocking and spying or SinonJS for a standalone library.

Then you can just write a test like that (using Sinon):

var mock = sinon.mock(window);
mock.expects("alert").once().withExactArgs("foo");

alert("foo");

mock.verify();

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