用JS實現前端開發單元測試(翻譯)

vitrum發表於2013-02-01

Front-end Unit Testing with JavaScript Posted on May 7, 2012 at 8:36 pm. Written by Danny Croft http://dannycroft.co.uk/front-end-unit-testing-with-javascript/

Unit testing can make your code less prone to bugs and gives you piece of mind that everything is working the way it should. Normally when I speak to other developers about work, we end up speaking about workflow, tools and release processes. I’m always surprised by the amount of front-end developers that don’t unit test their code. When asked why, they give the following answers:

“I did have a look at Selenium, but it freaked me out. Getting it installed and ready to go looked a right pig!” “The back-end guys usually just do that” “I don’t really get time to do any of that kind of stuff but I’d like to” “Unit Testing? Say whaaaaattt?” So rounding up the problems that people are facing, we get the following:

Time and effort it takes to get setup Complex APIs and steep learning curves General lack of exposure Introducing PhantomJS & CasperJS PhantomJS is a headless WebKit with JavaScript API. CasperJS is a navigation scripting & testing utility that runs on top/alongside of PhantomJS.

If you’re thinking “headless WebKit??!!?”, then it might be easier for you picture PhantomJS as a web inspector console that can be injected into any web page that you want, then accessed and used.

CasperJS makes it alot easier for you to navigate around a web page testing as you go. To be fair, my explanations don’t do these two tools enough justice. Please visit http://phantomjs.org/ and http://casperjs.org/ for a better explanation and more advanced features that aren’t covered here.

Both are really easy to use and extremely powerful!

Getting Started! Requirements:

Mac OSX Terminal app Ruby Git Homebrew First things first, your Mac probably already has Ruby installed (You can check by running “ruby -v” in the terminal) and you more than likely already have Git installed.

You will need Homebrew. Granted other package managers are out there, but you still need Homebrew in your life. I love Homebrew.

I’ve tried installing PhantomJS via other (non-package manager) methods and it was a shameful experience, trust me.

Don’t worry installing Homebrew is pretty damn easy.

Step 1: Open up the terminal and copy and paste the following into it. Hit enter. This may take a few minutes to finish.

/usr/bin/ruby -e "$(/usr/bin/curl -fsSL https://raw.github.com/mxcl/homebrew/master/Library/Contributions/install_homebrew.rb)" Step 2: Confirm Homebrew is all up in your system.

brew -v && brew help This will output the homebrew (brew) version number and the help menu, should you fancy a quick rummage around.

Step 3: Install PhantomJS. This may take a few minutes to run.

brew install phantomjs Anyone one that tried and failed to install PhantomJS using the downloadable executable will be kicking themselves now (me included).

Step 4: Has PhantomJS installed? Which version have I got?

phantomjs -v && phantomjs -h This will do the same as Step 2 but for PhantomJS.

Step 5: Install CasperJS. I’m assuming you have Git installed (rightly or wrongly). If you don’t then.. erm.. brew install git =). Run the following commands one after another.

Download CasperJS to a location that you’re happy with e.g. I download most software to a single location ~/src

git clone git://github.com/n1k0/casperjs.git Access the downloaded file and use Git to checkout the latest version of Casperjs.

Note: The version number may change so maybe run “git tag” first, which will give you all the versions available. Just pick the highest number available and if it differs from 0.6.6 then change the command below to use the latest version e.g. git checkout tags/0.6.7

cd casperjs/ && git checkout tags/0.6.6 Create a link to the CasperJS source file

ln -sf pwd/bin/casperjs /usr/local/bin/casperjs Check CasperJS is installed

casperjs --version Now just to verify that everything is installed in a suitable place please run the following:

which brew && which casperjs && which phantomjs Which should output something similar to the following:

/usr/local/bin/brew /usr/local/bin/casperjs /usr/local/bin/phantomjs Now that everything is installed and ready to go we can get started with some basic tests. For example purposes only I’m going to run and build the test in a folder called “unit_tests” on the desktop (very imaginative I know). Normally, you would have them checked in to your project repo so other team members can add tests and use exisiting ones.

cd ~/Desktop mkdir unit_tests cd unit_tests touch duckduck.js Now open up duckduck.js with your favourite text editor e.g. sublime duckduck.js or mate duckduck.js

Copy and paste the following code and save the file:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 // Add a title comment so that you know what's happening and when casper.test.comment('DuckDuckGo - Homepage');

// Setup any variables you may need. In this case we need a search term var search_term = "speed of an unladen swallow";

// Start casper running on a web page, in this case the awesome // duckduckgo seach engine. casper.start('http://duckduckgo.com/', function () {

// Check the title is "DuckDuckGo"
this.test.assertTitle('DuckDuckGo', 'Homepage has the correct title');

// Check the main search box is available
this.test.assertExists('#search_form_homepage', 'Main search box is available');

// Log out what we are doing
casper.test.info("Populating search box with term: " + search_term);

// Populate the seach box with a query
this.fill('#search_form_homepage', {
    'q': search_term
}, true);

// Log out what we are doing
casper.test.info("Testing search...");

});

// After the form has been submitted and results shown casper.then(function () {

// Test we got results back from our search query
this.test.assertEval(function () {
    return __utils__.findAll('div.results_links_deep').length > 10;
}, 'Returned search results for query');

});

// Run the whole test suite (all the above) casper.run(function () {

// Confirm this test is done
this.test.done();

}); view rawduckduck.jsThis Gist brought to you by GitHub. Now run the following in the terminal:

casperjs test ~/Desktop/unit_tests/duckduck.js You should get something cool like the following:

The above is just scraping the surface of what we can do. See http://phantomjs.org/ and http://casperjs.org/ for more information.

If you didn’t get the above result then please let me know what went wrong and we can update this to help others. Also, if you think I made a mistake or think something would be easier to understand, please let me know!

Tags: front-end, javascript, unit testing, web development

相關文章