Qunit Test in Javascript - javascript

I am using Qunit and I am newly Qunit to test my internal javascript functions, I want to use it also for some user interactions like testing error message after Jquery validations. Since I dont use HTML pages (I should test them on gsp, which requires a working runtime.) I dont know how to test them. Is it possible to test them on a given host name(like Selenium-tests)?

Is it really necessary to test your interactions against a real host? You could always use mocks and test only if your error messages are being called properly, without actually contacting any external elements. That's the whole point of unit testing, after all. I personally use SinonJS for that kind of thing. You could also check for other mocking frameworks if you like (e.g. JsMockito).
For more information about mocks and stubs, I'd recommend you to read this article and do a little research about it on Google's testing blog.

Related

How to test legacy jquery code

I'm starting to introduce TDD into an existing JavaScript/jQuery project.
Currently, I'm testing with Mocha and Chai under Grunt in a CLI shell in Emacs.
This works nicely for the parts of the code that are side-effect-free, synchronous, don't use jQuery, etc.
I've found many online articles addressing individual issues in setting up a more inclusive test environment, but I've not managed to find a good getting-started guide, without diving into the weeds of competing libraries and setups.
I don't need a "best" answer, nor anything too fancy. I don't even need mock button presses or user-input; I'm happy just testing my handler code.
Just looking for a guide or set of recommended best practices to test client-side JavaScript code where:
The existing code uses jQuery and AJAX;
The test environment should be running continuously;
The test environment should be launched from my gruntfile. Or, I'd be ok moving to gulp or any other similar driver.
Ideally, I'd like the tests to be running in an Emacs buffer. But, if need be, I'd be ok having it running in another window that I can stick in the corner of my screen;
Tests should run reasonably fast. I want them to trigger automatically on every file save.
I think I'm describing a very vanilla set of test requirements, so I'd expect there to be common answers. But, my search-fu must be low today because I'm not finding what I want.
If you're using Mocha and Chai, then you already have the basics set up.
If your code under test modifies the document, you can substitute an artificial document for your tests (via jsdom).
If your code under test fires Ajax calls and you'd like to test them, you can use sinon to put a fake XMLHttpRequest provider. sinon also offers a convenient mock for setTimeout and the family.
If the code under test uses jQuery, then you can either separate the jQuery-dependent part, or just run jQuery on the server using the jsdom document. jQuery installs with npm easily.
If all of this seems not realistic enough for your purpose and you'd like a more true environment, you can have a look at karma - it's an automation tool that can open a browser in the background, run any tests inside and report the errors in the console. It's much slower than mocha but you get to run your code (and tests) in a real browser, perhaps even several browsers at the same time.
Both tools have their places, e.g. you could use mocha for testing vanillajs and simple DOM modification (also e.g. React components if you're into that), and resort to karma for writing slower, more realistic tests that depend more on real browser behaviour.

How to do a smoke Test and Acceptance test in a Javascript Aplication?

I want to do a smoke test in order to test the connection between my web app and the server itself. Does Someone know how to do it? In addition I want to do an acceptance tests to test my whole application. Which tool do you recommend?
My technology stack is: backbone and require.js and jquery mobile and jasmine for BDD test.
Regards
When doing BDD you should always mock the collaborators. The tests should run quickly and not depend on any external resources such as servers, APIs, databases etc.
The way you would want to make in f.e. Jasmine is to declare a spy that pretends to be the server. You then move on to defining what would be the response of the spy in a particular scenario or example.
This is the best aproach if you want your application to be environment undependent. Which is very needed when running Jenkins jobs - building a whole infrastructure around the job would be hard to reproduce.
Make spy/mock objects that represent the server and in your specs define how the external sources behave - this way you can focus on what behavior your application delivers under specified circumstances.
This isn't a complete answer, but one tool we've been using for our very similar stack is mockJSON. It's a jQuery plugin that does a nice job both:
intercepting calls to a URL and instead sending back mock data and
making it easy to generate random mock data based on templates.
The best part is that it's entirely client side, so you don't need to set up anything external to get decent tests. It won't test the actual network connection to your server, but it can do a very good job validating that type of data your server would be kicking back. FWIW, we use Mocha as our test framework and haven't had any trouble getting this to integrate with our BDD work.
The original mockJSON repo is still pretty good, though it hasn't been updated in a little while. My colleagues and I have been trying to keep it going with patches and features in my own fork.
I found a blog post where the author explain how to use capybara, cucumber and selenium outside a rails application and therefore can be use to test a javascript app. Here are the link: http://testerstories.com/?p=48

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();

Test driven development for a JavaScript library

At the moment I'm working on a JS library for a webservice, you can compare it with Twitter Anywhere. Now i want to make it more test-driven.
It's not easy to test because it has to work on every site that wants to make use of it, and of course with every browser.
How can i test the library efficiently?
All the API requests and responses are in JSON, is there a good way to test these calls?
I know about Cucumber and js-test-driver.
Greetings,
Chielus
Javascript language is dynamic by nature, so it is really test-driven friendly. I've recently got a little experience with javascript testing. I've rewrote major javascript components using TDD and got clear desing and more compact code!
unit test framework of choice is qUnit. It is very easy to start with testing.
functional test framework of choise is funcunit.
I did a blog post of testing REST api with FuncUnit here.
If you need some examples of tests and implementation, you can check my github repository.
Don't ask questions, just start testing :)
If you know about jsTestDriver I think you've already found a good solution?
You can use it to automatically launch your tests in multiple browsers and return success or failure.
This sets it apart from other tools that use headless browsers, as with jsTestDriver you're running your tests in real browsers, which seems to meet your requirements.
jsTestDriver comes with its own limited assertion framework but you can plug others into it including QUnit, YUI and Jasmine.
You said above in relation to Jasmine, "I don't think i can do BDD, because it's a library that has to work with all kinds of sites.". I'm not sure what you mean by this?
Jasmine provides all the assertions to let you do the same tests as QUnit. It also lets you 'spy' on Ajax callbacks, intercept the JSON to examine or even alter it, then pass it on to your default callback. With this you could check the JSON response then check again when your UI has reacted to it in the right way.

What are some JavaScript unit testing and mocking frameworks you have used? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
My main JavaScript framework is jQuery, so I would like my unit test and mocking frameworks to be compatible with that. I'd rather not have to introduce another JavaScript framework.
I am currently using QUnit for unit testing and Jack for mocking, but I am pretty new to the whole unit testing of JavaScript.
Is there a better tool to suggest? What has worked for you?
I think that Jack is the best mocking framework for JavaScript as of the time of this writing. The main reason is that what's right for JavaScript is not likely what is right for a strongly typed language such as Java.
Many JavaScript mocking frameworks are inspired by Java mock frameworks (such as the excellent JsMockito, for example). But the problem with these is that they require dependency injection, because that's about the only reasonable way to use mocking in Java. But in JavaScript, there are many ways to use mocking, and you are not forced into using dependency injection everywhere.
For example, with JsMockito, you have to make mocks and then pass those mocks into your software-under-test (SUT). The SUT has to directly call the mocks. Therefore, you're forced to code the SUT as a constructor or function that takes in all its dependencies as parameters. (Sometimes, that's a fine way to implement it, but not in every case. The tail is wagging the dog if your mocking framework's design forces your implementation approach.)
In JavaScript, it's very easy to "hijack" any function. Therefore, there are tons of ways to build something such that you can mock parts of it without explicitly injecting its dependencies into it. For example, Jack lets you mock any function, whether it is public or on a local object. From there you can spy on it, stub it, or express expectations on it. The key point is this: once you've mocked a function, any calls to that original function will instead be directed to your mock. In other words, your mocks will still get used even though the original, un-mocked function was called. As a result, you are not forced to inject dependencies, although you certainly can do so in those cases which call for it.
JavaScript is a different language than Java (and C#, etc.). It allows for different implementation idioms. Dependency injection is still one valuable tool in the toolbox in JavaScript, but it is not the only game in town any more. Your mocking framework needs to know and respect that fact. Jack and a couple of others do, but of the ones that do, Jack appears to be the most mature and feature-rich.
QUnit
jqUnit
Writing JavaScript tests with QUnit and jqUnit
QUnit is the unit testing framework for the jQuery JavaScript framework. The testing framework itself uses the jQuery library, but the tests can be written for any JavaScript and do not require the code to use jQuery.
jqUnit is a modified version of QUnit that adds in the setup, teardown, and assert functions that are more typical of an xUnit framework, and encapsulates everything in one global variable.
The visual interface of the testrunner page is nice, allowing you to drill down and see each assert in every test method. Writing tests is fairly easy, and you can run the test code directly on the testRunner page [8]. This allows for easy and visible DOM testing.
QUnit: MIT or GPL (choose) jqUnit: MIT License
Pros
Asynchronous support
Good for DOM testing
Tests always run sequentially in the order they are added to a suite
Debug on test page using firebug
Syntax is similar to JUnit if using jqUnit, but simple to learn if using QUnit
Cons
Automation would be difficult to implement
I'm not sure why no one has mentioned JsTestDriver! It has to be the one of the only JavaScript testing tools that actually work like you'd expect them to if you've used unit testing tools in other languages.
Running tests can be done without touching a browser, you can integrate it with IDE's, and you can integrate it with Continuous integration systems... Oh, and it's fast, and can run tests in multiple browsers at the same time.
You can also use other testing frameworks like YUITest with it, making it even better.
YUI Test
TDD With YUI Test
YUI Test is the test framework for Yahoo’s User Interface (YUI) library. It is used by Yahoo to test its own library, and has syntax similar to JUnit.
Like jsUnit, YUI Test comes with its own logging console that can output information, warnings and errors in addition to the results of each test.
YUI also provides the ability to send reports on the results in either JSON or XML format.
YUI Test is BSD licensed.
Pros
Really good documentation
Active community
Regular releases
Syntax is similar to JUnit (test suites, asserts and setup/teardown)
Asynchronous support
Good for DOM testing
Tests always run sequentially in the order they are added to a suite
Cons
Automation not trivial to implement, but less difficult than other frameworks
Also check out
http://sinonjs.org/
It has test spies, test stubs, mocks, fake timers, fake XMLHttpRequest (XHR), fake server, sandboxing, and assertions
It does work along with QUnit and that has been a plus so far.
This is a pretty good review of mocking frameworks available for JavaScript:
http://testdrivenwebsites.com/2010/05/06/java-script-mock-frameworks-comparison
I use the Screw Unit test framework and I've written my own mocking library called jsMocha which has been in heavy use in the company I work at for over 6 months.
For mocking in JavaScript, take a look at qMock, a framework a colleague and I wrote to complement our use of QUnit. Although the latter is great for unit tests, it doesn't allow for very effective async/business logic testing. We haven't 'tagged' any release as stable, but there's some decent documentation on there, and if you checkout the SVN repository you'll see qmock itself has unit tests behind it which are fairly self-explanatory.
Oh, and to automate testing as part of the build, we used a simple Selenium script to navigate through our testsuite (one testing page per JavaScript file), and 'listened' for a pass or fail CSS class (added by QUnit). This works headless as well for Internet Explorer and Firefox 2, AFAIK.
For Firefox development, I have fallen in love with UXU, based on MozUnit, but it is still active. It has nice features, like a mock server and sleep / yield methods.
CrossCheck seemed extremely powerful when I looked at it, but we've not incorporated it into our build process at this time. It has the advantage of being browserless, and thus should work well in an automated build-and-test scenario.
http://thefrontside.net/crosscheck
I know you are asking for jQuery-compatible frameworks, but I want to throw script.aculo.us into the mix for completeness. They have a unit test suite that isn't bad.
JsUnit is run from either the browser, through its Eclipse plug-in, or automatically through an Ant task. You create an HTML page with a bunch of test functions, which must be named with the prefix ‘test’, include the JavaScript file you are testing. When any assert within a function fails, the entire function fails and stops executing. There is no guaranteed order in which these tests are run. You can create setup() and teardown() functions.
License: GPL, GLPL, and MPL
Pros
Automation is relatively easy to implement
A lot of functionality
Syntax is similar to JUnit
Cons
Not great for DOM testing since it runs tests inside an iFrame.
No guarantee that tests will be run in the order they are written.
Can’t use Firebug on the testrunner page. Need to have another tab open with the actual test code.
We've been using jsspec. It's very nice if you like rspec and BDD. I just saw an article by Justin Gehtland on using it "headless" as well.
You could try HtmlUnit which had a jQuery compatible release over a year ago.
The advantage of HtmlUnit is that it isn't driving a browser, so it is fast.
The downside is that it isn't driving a browser so there are some JavaScript things that won't work. But offsetting that they can run the jQuery tests so the JavaScript support might be good enough for what you need.

Categories