Testing javascript code. Modular testing of JavaScript code: strategies, libraries, tools. PhantomJS problems on Windows

Golovna / Usunennya malfunctions

Creating effective test cases can be extremely important for great projects, as the behavior of parts of the program can change for various reasons. Perhaps, the most problem is, if a large group of retailers work on it, but on sum modules. You can cause unplanned changes in the behavior of functions written by other programmers. Abo the robot in the style of the term to bring to the inevitable change of critical parts of the program.

Testing with web programs sounds like a visual assessment of the elements and an empirical assessment of the practicality of the functionality. Tobto in the transition along the divisions and scoєnnі diy over the dynamic elements.

Over the years, the project will be reminiscent of new functionality, what will it take to complicate the process of re-verification of yoga robots. For automating vicorist module (unit) testing.

Іsnuyu 2 approach to induce test scenarios:

  • white boxtesting– written tests are based on the implementation of the functionality. Tobto. we revise for the same algorithms, which will have robotic modules of our system. Such a pidhid does not guarantee the correctness of the robotic system.
  • black boxtesting- The creation of scenarios is based on the specifications and capabilities of the system. So it is possible to verify the correctness of the results of the work and all the programs, the prote similar pidkhid does not allow to make other and rudimentary pardons.

Cho testuvati

It may be possible to know what kind of skin function tests were carried out, how did you implement it. We don't call it that. Writing tests takes an hour of the retailer, to optimize the process of working on the varto programs, prepare tests for more foldable, critical, and quiet functions, so that they can lie in the results of the work of other modules of the system. Cover the ambiguous logic with tests, in which case you can blame pardons. Also varto to create tests for these code holders, as in the future it is planned to optimize, so that after the optimization process it is possible to reconsider in the correctness of their vikonannya.

It is important to carefully evaluate the results of the test to clarify the terms of the distribution. Of course, if you are not cold at the hour, then you can allow the skin function to be covered with tests. Ale, the sounding of the investigation is carried out at a very short time, and it is necessary to conduct an analysis of the well-known retailer of intelligence, where it is necessary to carry out the test. In addition, the writing of tests suggests the varity of the project.

In this order, it is possible to formulate 3 vipadki, if the unit test is correct:

1) As a father-in-law, give the opportunity to show a pardon, lower for a great joke.

2) Reduce the hour for pleasure

3) Allows you to test code that changes frequently.

The three main components of the frontend (HTML, CSS, JavaScript) need to be tested, maybe even JavaScript code. CSS is reviewed exclusively by the visual method, if the retailer/tester/replacer is reviewed graphical interface in different browsers. HTML - markup is rewritten in the same way.

Yak testuvati

When prompting scenarios for conducting tests, follow the following principles:

  • Your tests may be as simple as possible. Then there will be more efficiency of that which, on the results of this exercise, will add the very same bug, which you are trying to repeat.
  • Decompose tests of great modules. It is best to know the specific place of pardon.
  • Rob testi independent. The result of one test at the same time is not to blame for the fall in the results of another.
  • The results of the tests carried out may be repeated again and again. So, if you run the test again, the result can be the same as the last time.
  • For any kind of pardon, the Vikonan program may have creations of a test script. In this rank, you will be convinced that the bug is effectively corrected and does not appear in coristuvachi.

Chim testuvati

For unit-testing js-code there are a few libraries. Perhaps the widest is QUnit. To carry out unit tests for the help of the library, we need to create a “pisochnitsa” - a simple html-side, in which there will be a library for testing, a code that needs to be tested, and the power of the test itself.

Functions for tests:

(function() ( window.stepen = function(int) ( var result = 2; for (var i = 1; i)< int; i ++) { result = result * 2; } return result; } window.returnFunc = function() { return "ok"; } })();

Test listing:

Test("stepen()", function() ( equal(stepen(2), 4, "2^2 - equal method"); ok(stepen(3) === 8, "2^3 - ok method" );deepEqual(stepen(5), 32, "2^5 - deepEqual method"); )); asyncTest("returnFunc()", function() ( setTimeout(function() ( equal(returnFunc(), "ok", "Async Func Test"); start(); ), 1000); ));

As you can see, QUnit supports 3 functions to match the results of matching code with validation:

  • ok()– check if the test is successful, if the result is to turn = true
  • equal()- Match the result with scoring
  • deepEqual()- Matching the result with scoring, rechecking the type

Result of vikonanny:

As you can see, the QUnit library conducts code testing once for a number of browsers.

Use of other libraries for unit tests. However, the concept of stimulating scenarios for testing in them is the same, so having sorted out one thing, it is not important for you to switch to another language.

It is important to remember

The peculiarity of the current js-code is the asynchronous nature of the visualization. Libraries for testing may be able to perform asynchronous tests. For example, if you try to protest the function, for example, send a get-request to the backend and turn it back on, then in order to conduct tests, you can run the stop() function, run the function that is being tested, and then restart the process using the start( ) , "Wrapped Yogo" in setTimeout(). Tobto. you are guilty of laying down such a gap to the hour, by the stretch of which may the function will be completed. It is necessary to diligently choose the trivality of this winding, .k. From one side, the robot tried the method, it is possible, as singularity and to induce the need for a specific implementation of the reporting functionality, and incorrect behavior.

Testing Backbone add-ons

For the purpose of testing add-ons, written with Backbone.js hacks, we will describe the project in .

Modular tests can be tested:

  • Correctness of creation of models and controllers
  • Correctness of data for models
  • Vikonannya methods of controllers (for which stink you can turn the result)
  • Successfulness of interest

Test code:

Test("Backbone.js", function() ( ok(sample, "Namespace check"); ok(sample.routers.app, "Router check")); ok(sample.core.pageManager.open("chat" ) , "Page opening test (Controller method call)") ok(sample.core.state, "Model check"); "); html(data); return data; )) ), "Template loading check");

The result of the work with pardons testing:

Test run automation

As a rule, the program's throating is for the managers, as it is necessary to do it often with intensive growth. Therefore, automate this operation. Mimic Jenkins is a tool for seamless integration. The idea is based on the deployment through Jenkins from the automatic tests carried out.

QUnit tests are run in the browser. Get around these features to help us with phantomjs - a software that emulates the browser's robot. The phantomjs retailers have already provided a script for QUnit testing, a prote for the correct robot had a little bit of additional work.

/** * Timeout test mind is true or timeout occurs. * Useful for waiting * on a server response or for ui change (fadeIn, etc.) to occur. * * @param testFx javascript condition that evaluates to a boolean, * it can be passed in as string (e.g.: "1 == 1" or * "$("#bar").is(":visible")" or * as a callback function. (":visible")" or * as a callback function. * @param timeOutMillis max amount of time to wait. If not * specified, 3 sec is used. = timeOutMillis ?timeOutMillis: 3001, //< Default Max Timout is 3s start = new Date().getTime(), condition = false, interval = setInterval(function() { if ((new Date().getTime() - start < maxtimeOutMillis) && !condition) { // If not time-out yet and condition not yet fulfilled condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code } else { if(!condition) { // If condition still not fulfilled // (timeout but condition is "false") console.log(""waitFor()" timeout"); phantom.exit(1); } else { // Condition fulfilled (timeout and/or condition is //"true") console.log(""waitFor()" finished in " + (new Date().getTime() - start) + "ms."); typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it"s supposed to do once the // condition is fulfilled clearInterval(interval); //< Stop this interval } } }, 100); // repeat check every 250ms }; }; if (phantom.args.length === 0 || phantom.args.length >2) console.log("Usage: run-qunit.js URL"); phantom.exit(); ) var page = new WebPage(); // Route "console.log()" calls from in the Page // context to the main Phantom context (i.e. current "this") page.onConsoleMessage = function(msg) ( console.log(msg); ); page.open(phantom.args, function(status)( if (status !== "success") ( console.log("Unable to access network"); phantom.exit(); ) else ( waitFor(function() ( return page.evaluate(function()( var el = document.getElementById("qunit-testresult"); if (el && el.innerText.match("completed")) ( return true; ) return false; )); ), function()( var failedNum = page.evaluate(function()( var el = document.getElementById("qunit-testresult"); console.log(el.innerText); try ( return document.getElementsByClassName("fail" ) ).innerHTML.length; ) catch (e) ( return 0; ) return 10000; )); phantom.exit((parseInt(failedNum, 10) > 0) ? 1: 0);

To display the results in the console about the results of the script with tests, it is necessary to add the logging function.

Code testing- Invisible cycle of development software. Most of the developers often underestimate its role and revise the practicality of the programs in the old way - "practice, that's good." Early on, this strategy gives a hit and a bug tracker starts to suffocate an unnamed army of tractors. Sob not to eat in such a pasta, I recommend once and for all to study the nuances of testing JavaScript code.

JavaScript is not the same

Today JavaScript- it's not just a mova for povzhavlennya sane looking programs. The hours when JavaScript was hacked for frying or preparing menus were irrevocably gone. Now it’s independent language, but it’s good to practice both on the client and on the server. The role of JavaScript has been steadily promoted, which means that when writing the code, it is necessary not to bother with practices that have proven themselves well in other programming languages.

What can I do with respect to practices and paradigms? Well, the architectural template MVC (model view controller) that pattern organization code. Following this tricky tricks, you can write a better code, which will not only be easy to maintain, but rather build up to automatic testing.

Pardon for more testers

It's not a secret for anyone that the most popular way of testing was the banal reversal of the "eye". Its essence is simple to dissimilarity - having written a thousand rows of code, executing the task and launching your own vitvir. After digging, clicking - everything works, you can upload it to the combat server. Everything is borderline simple and with proper attention of the retailer (ideally, a good person for a “tester”), you can rely on the correctness of the robotic programs.

In practice, everything seems to be different. Don’t ring out the sound of an okremnogo testuvalnik. The rozrobnik itself tries to reconsider the practicality of the programs, violating the sequence of the technical manager. More advanced forge code to automate similar integration testing for additional speeches on the Selenium kshtalt.

In this manner, the programmer will take away the opportunity to show only a rude pardon. Unfortunately, "stupid" and "non-performing" di koristuvach, as well as being cunning in business logic, in 99% of the speeches are left behind the scenes.

The presence of an okremoi person in the person of a tester also destroys the problem often and until the singing hour. If you want to show your sapper respect to the details, then the quality of your testing will be reduced to zero with the increase of the addendum. I will give an example from practice.

As if I were entrusted with the development of a small program. For the functionality of the project, guessing the simplest CRM, how I realized the shortest term. Having taken off the vineyard, I handed over my vacations to the deputy and forgot about the project for the spring months. Dali started naytsіkavіshe. Zamovnik Virishiv seriously expanded the functionality of the program and called me for help. Naturally, I took up and began to work a new function after function. The back of the head was not coherent, but if it went right to the deep integration of the functional, the jiggly rіy bagіv rushed into my bіk. Shmatki code began to conflict, and it was possible to waste a lot of time to resolve conflicts. “But if you’re not a bachelor, what’s the problem with your appendix?” - Ask respectful readers. Having launched, but through those that the addendum had grown, it didn’t take me corny an hour and nerves to protest all the functionality en masse. I meddle with a test of less than a few functions and paid generously for the price. The moral of the tale is “Think about testing as an invisible part of the development.”

Unit testi yak sribna kulya

Save your nerves and improve the performance guarantees of the few parts of the program, which is the best way to help modular testing. If I haven’t stumbled on this terrible word more than once, I’ll explain briefly. Modular tests allow you to automate the testing process and to test the skin function of the program.

After the completion of the development of a new function (possible variant of writing tests before the beginning of development), the developer writes a special code to test his code. For the code for testing, it is necessary to observe the different situations and the values ​​that are being rotated. For example, we wrote a function to trim gaps. In order to protest її practice, we are guilty of preparing a sample of tests, in order to allow us to assert that:

  • when transmitting a row "row" on the output, we take "row";
  • when transferring the term "row 9" on the output, we take "row 9";
  • We can also add a test for other input parameters (for example, replace the character of the probe with a tab). Zagalom, the more we cover the code with tests, and the more possible negative options, the more chances, that the most important moment on the head will lose three hairs.

    In the world of JS, tests are described for additional specialized frameworks. They have everything necessary for the description of tests, as well as sleazy tools for systematizing feedback about the progress of the test.

    Testi! = initial code

    Rozrobnikov, yakі not vikoristovuyut unit-testuvannya, love stverzhuvaty, scho unit testing vmagaє writing and pіdtrimki dodatkovogo code. Movlyav, terms in real projects are most often stylistically and writing advanced code is simply not possible.

    I’ll be fine with the stale terms, but I’m ready to get ahead of the code. From one side, so, the tests will read the additional code, and also, an hour on the yogo of writing. From the other side, this code is violating the role of airbags in cars and will definitely pay off with increasing programs.

    If you don’t have time to torment the bazhannya, think about the writing of tests - three times. Maybe in this time more expensively cover with tests the most cunning worker of the code, and not be forced to test the same way. Forever think with an eye on the future, or in a month your program can grow to unprecedented growth.

    Not all code is tested

    Why do I insist that it is necessary to think about testing before writing the main code? Because the code that is often handed over to unit tests is written in a different style. Not every code can be protested. The code, in which the logic of that manifestation is combined, it is impossible to protest normally. Here I will make the raja dorimuvatsya a lot of simple rules:

  • Not a trace of writing great functions. Skin function is to blame for one problem, not 100,500 possible situations. For example, it is not necessary to enter the data management code on the server at the function, which is charged for the preparation;
  • The function that is added over 10 rows in the code is faster for all the filthy function;
  • The logic of that manifestation in any case is not to blame but at the same time;
  • QUnit - a classic of the genre from the creators of jQuery

    QUnit become particularly popular among JavaScript retailers. First, it's well documented and easy to use, but otherwise it's created by the authors of jQuery. The library is suitable for testing code created on the basis of jQuery, as well as JavaScript.

    Zavantageity the rest version You can use QUnit from the official site - http://qunitjs.com/. The library is supplied by looking at one JS that css file. Let's say that you have learned from the necessary components, and if so, then it's time to write a trial test. Let's not go far and try to protest the guesswork of the trim() function.

    To demonstrate the tests, I created the simplest project from the next constructor:

    Index.html - the main file, which displays the test results; - qunit-1.12.0.js – qunit library file; - example.js - a file for testing the code for testing (for example, the description of the trim() function); - test.js - file with tests; - qunit-1.12.0.css - styles for designing a star with tests;

    In the file index.html and test.js of the representations in listing 1 and 2. Most of us click on another listing, in which the function that is being tested (trim()) and the code of the tests for reviewing the practicality is pointed out. To be fair, the trim() function itself might be outdated, I'll put it in another listing just to save space in the magazine.

    Now let's look at the tests themselves. For zdіysnennya reverification of the praceszdatnosti of our code qunit.js teach us low methods:

  • test()- Obgorka for the description of the test;
  • ok()- Confirmation allows you to verify the truth of the first parameter. In our application, I pass it a quick call to the trim() function and match these values, so I check the trim. Yakshcho umova is true - the test is passed;
  • equal()– the method allows to reverse the validity of the first and the other parameter. I’ll give you best respect, scho given method vykonuє not strict reverb, that suit only scalar quantities;
  • notEqual()- Extended equal(). Vikonuєtsya, as if it is more important, not more valuable to another;
  • strictEqual()–similar to equal() with only one extra check – in victorian strict revalidation (that is, reverifying the type of data);
  • notStrictEqual()– protractile method strictEqual();
  • deepEqual()– a method for recursive solids that can be used for primitives, arrays, objects;
  • notDeepEqual()– prolongation method deepEqual();
  • raises()- Validated for testing the functions of the turnaround, which generates winklets;
  • In another listing, I first showed how to set up qi methods in a practical way. If you run a test butt in such a way, all tests will be successfully passed (divine young baby). In order to support the difference between successfully passed tests and end with pardons, I changed the code of one test a little. Have a row of dough for help strictEqual() I added a pardon result (divine young baby).

    Listing 1. In the index.html file

    Testing for help with QUnit

    Listing 2. Test files and trim() function

    function trim(string) ( return (string || "").replace(/^\s+|\s+$/g, ""); ) test("Test function trim()", function() ( ok(trim ("test") == "test", "there are extreme gaps"); ok(trim("1") == "1", "a lot of holes in the sides"); = "24", "trim that tab from sides"); equal(trim(""), "", "Empty row");

    3 tests simple functions nachebto razіbralisya. Accept me, add nothing more. Then you need to take the real code and try to write tests yourself. We marvel at something else, often blame the task before JavaScript-Retailers - testing asynchronous functions. The program, stuffed with JavaScript code, 99% interacts with the server part for the help of Ajax. It is also impossible to leave out the code without re-verification, but the writing of the tests looks like a trio otherwise. Let's look at the example:

    AsyncTest("myAsyncFunc()", function() ( setTimeout(function() ( ok(myAsyncFunc() == true, "Data passed successfully"); start(); ), 500); ));

    The main thing is to check the butt of the front one - the test() wrapping is replaced by asyncTest(), which itself declares that it is less asynchronous to test the test itself. Next, I start the hour of ochіkuvannya 500 ml. sec. For one hour, the myAsyncFunc() function is responsible for sending data to the test server, and so everything turns true. The axis here comes by itself ticking moment. When the asyncTest() call is called, it will continue to run and after the test is completed, you need to run it yourself. For flow control QUnitє start() and stop() methods.

    Testing asynchronous functions with help of the library QUnit it is easy to win. The rest of the butt, which I wanted to draw, to tie from the written test, which vikonu a kіlka of asynchronous perevіrok. A smut food, as if blaming it on tsimu from similar tasks, is the best place to start the stream of vikonannya. The official doc encourages you to stop at such situations like this:

    AsyncTest("myAsyncFunc()", function() ( expect(3); //Three retests work here ok(myAsyncFunc(), "Light is better than 1"); ok(myAsyncFunc(), "Light is better than 2") ) ok(myAsyncFunc(), "It should be faster than 3"); setTimeout(function() ( start(); ), 3000); ));

    Test for diy koristuvach

    Keep in mind that JavaScript is written with a lot of interface stuff. For example, a koristuvach clicks on pіmpі and at the same time on yogo click can be status. Similar "interface" code in projects is too rich and it is also necessary to cover it with tests. Let's wonder how you can model the onslaught of keys and write a test for this one. We can see that we can be a function, as if the keys are pressed. Її the code I have found in the third listing:

    Listing 3. Logging keystrokes

    function KeyLogger(target) ( if (!(this instanceof KeyLogger)) ( return new KeyLogger(target); ) this.target = target; this.log = ; var self = this; this.target.off("keydown") .on("keydown", function(event) ( self.log.push(event.keyCode); )); )

    Now let's try this protest function. Nasampered, at this test, we need to eliminate the pressed key. It's easier to ask for help from the library jQuery, which allows you to create a pod into a kilka row of code (div. listing 4).

    Listing 4. Test code for KeyLogger

    test("Key Logging Test", function() ( var event, $doc = $(document), keys = KeyLogger($doc); event = $.Event("keydown"); event.keyCode = 9; $doc .trigger(event);equal(keys.log.length, 1, "Key logged");

    On the cob of the listing with the test, I am preparing a pod for emulation of the pressing of the key - "keydown". We are pressing the Tab key (code 9). Then, for the help of the trigger() method, I'll fix the prepared pod, after which you can proceed to the test. Back to back, I’m revisiting the big picture - what a key was pressed, and then we’ll code.

    DOM for close tests

    Once qunit.js If you allow tests to be written for the DOM, then there are no problems with writing tests for the DOM. That's right, and pointing butt lower to confirm my words. I am not commenting on yoga, just look at the code and you will understand everything:

    Test("Adding a new div element", function() ( var $fixture = $("#qunit-fixture"); $fixture.append("

    Price new div
    "); equal($("div", $fixture).length, 1, "New div successfully added!"); ));

    Phantom.JS - run tests from the console

    Write tests for the help of the library qunit.js manually and simply, ale early chi pizno її you see the need to automate the launch of the test and the selection of results. For example, I have to help virtual machine in DigitalOcean, what I can do for the help of the console.

    The phantom.js project allows you to elegantly solve this problem. Tse is not a hell of a framework for writing Unit tests, and the full console version of the engine webkit. To put it simply, the program is a browser. For the help of phantom.js, it’s really not just to automate the re-verification of tests, but also to fail the impersonal task, as early as it is too early to blame the retailer: removing the results from rendering the sides of a file (png, jpg), the functions of the tiling monitor (the swidth is entangled, it’s thin is productive) . etc.), emulation diy koristuvach toshcho. I recommend that you do not swear and read the official documentation for any project that you know for yourself.

    Phantom.js you can choose different platforms (nix, mac OS X, windows). If you are expanding everything under Windows, then there are no daily problems - download the binaries ahead of time. Minor startup problems can be caused if you have two video adapters installed, one of which is NVidia. In which way you happen to be quick with a hack, we will describe it in vrіzanny.

    Let's try to get to know phantom.js in practice. shob skip through phantom.js tests, prepared in the past, and then displaying the results in the console, we need a special script-loader - run-qunit.js . Open the console (I use Windows, that's the vicorist cmd) and type the command in the format:

    phantom.exe<путь к run-qunit.js> <путь к странице с тестами>

    In my opinion, the launch command looked like this:

    E:\soft\phantomjs>phantomjs.exe E:\temp\testjsforx\qunit\run-qunit.js file:///E: /temp/testjsforx/qunit/index.html Result її vykonannya: Tests completed in 2592 milliseconds . 9 ratings out of 9 passed, 0 failed.

    All tests passed

    Covering the code with tests is definitely necessary and it doesn’t matter what scale the program is being created. For a moment, I guess, some of the most popular programs are transformed into unwieldy monsters, which need to be improved and added functionality. Good coverage of the code with tests is a guarantee of success and quality. So, it’s not easy to start writing code for automated testing, but it’s not easy, but all the flour will pay off in the future. On whom I have everything for today, good luck!

    If there is no time for testing

    For the time being, there is no sense to write tests for simple functions (take the same trim() from the application in the article), rather focus on the most critical cases of the code. Dotrimuvatisya tsgogo rule sled when writing the code, which is often changed. The technical tasks of a live project are often changed, and the actual functions must be constantly updated. Such changes can cause unacceptable moments - with new changes, the code works well, but the old is not organically over-etched. Axis schob not to slander a feil here, similar functions are more likely to be covered with tests. Remember a simple rule - don't have time to cover the entire code with tests, covering the most important part of it.

    Good test rules

  • The test can be as simple as possible. The more foldable test, the more courageous will be allowed to pardon new ones;
  • Tests need to be grouped on modules, so that later it would be easier to know pardons and the ability to test parts of the program;
  • Skin test and deposits in other tests;
  • Always write an okremia test for skin manifestations of bugs;
  • phantom.js issues on Windows

    So it already happened, but apply everything to the stats, I tested not in Linux, but under the good old Windows 7. It appears that phantom.js may have small problems when working on systems where video adapters are victorious. On my laptop, the cream of the integrated video chip, NVidia still hangs out and via phantom.js categorically responds to the phantom.exit() command. As a result, the phantom.js process did not complete its work after the script ran out and continued to hang in memory. At the same time, the terminal also reacted to the completion commands (ctrl + c - without help).

    How do you get stuck with a similar problem and plan to win? phantom.js on Windows, then get ready to attack the offensive hack. Vіdkriy panel keruvannya Nvidia. Find the "3D Settings" item in the tree. From the right side, the option “Most important graphics adapter". For zamovchuvannyam її value is set at "Avtovibor". We need to remember the high-performance Nvidia processor or integrated graphics. After some simple trick phantom.js having begun to behave aurally.

  • Cristian Johansen Test-Driven JavaScript Development is one of the few books that looks at JavaScript from the perspective of writing tests;
  • John Resing, Beer Bibo "JavaScript Ninja Secrets" - garne book, so that I will be in good luck in the first year of JS to the retailers from the middle level of training. The book examines in detail the power of writing an effective cross-browser code, the nuances of processing the code and a lot of other flavors.
  • Testing for knowledge of upcoming topics is now available on the site: HTML, css, JavaScript, PHP, SQL.

    Skin test is cumulative 10 feed on the songs of those. I've tried in skin nourishment to deal with the most addictive spheres of stosuvannya specific language, so that you can reverify your knowledge as much as possible.

    Crazy, everything dough-free and go through them, be it.

    Test order:

    1. Go for help Rozpochati testuvannya in a viable test.
    2. Vіdpіdaєte on the supply, single correct option.
    3. After the completion of the test, you will be welcome your ball, number of pardons, as well as skin nutrition selection from the test.

    Respect! If you don’t see it until you turn to the front, then you must first prove it, think.

    Available at the moment of testing

    1. HTML

      • Usogo test passed: 75424 individuals
      • Average score: 2.83 out of 5 baliv.

      Basic knowledge test HTML. You need to know the basic HTML tags, and learn more competently їх voicing. It is also necessary to understand the features of the standard XHTML 1.1.

    2. css

      • Usogo test passed: 32828 osib
      • Average score: 3.37 out of 5 baliv.

      The test checks the knowledge of the basics css. To successfully pass the test, you must know the main types of selectors (syntax), know the main power and their possible values, and also know the recognition of the most popular pseudo-elements.

    3. JavaScript

      • Usogo test passed: 24845 osib
      • Average score: 3.31 out of 5 baliv.

      This test tests your knowledge of JavaScript. Nutrients from the dough are torn apart by various spheres of stosuvannya tsієї mov. Even richer food for the understanding of "dribnih" nuances. Otherwise, you will need to know basic speeches: work with changes, basic functions of JavaScript, priorities of operations and more.

    4. PHP

      • Usogo test passed: 33239 osib
      • Average score: 3.03 of 5 baliv.

      This test checks your knowledge of the PHP language. You will need knowledge of the main PHP constructs, work to change, session, implementation of redirect and other standard speeches
      Perekonlive prohannya: At the test, ask a lot for a check: "Who did you write the script for?". Great prohannya, do not need to copy yoga and revise it. Be honest with yourself.

    5. SQL

      • Usogo test passed: 18014 osib
      • Average score: 3.28 out of 5 baliv.

      This test is reviewing your knowledge of the movie SQL query. The zapitanya torkayutsya less themselves basic knowledge tsієї move, without any kind of destruction. You will need the most advanced SQL queries, as well as more competent words.

    І є jQuery official testing tool. Ale QUnit is suitable for testing any JavaScript code and to start testing server-side JavaScript behind additional mechanisms such as Rhino or V8.

    If you don't know the idea of ​​"modular testing", don't get confused - there is nothing foldable for understanding:

    "Modular testing or unit-testing(English) unit testing) - the process of programming, which allows you to check for correctness Okremі modules output code of the program. The idea is to write tests for the skin non-trivial function of the method. Tse allow me to file a quick reverberation, chi did not call the black change to the code before regression so that before the appearance of pardons, the programs have already been tested, as well as the easier manifestation and adoption of such pardons.

    Significantly cited from Wikipedia. Just create tests for the skin functional block of your code, and as soon as all the tests are passed, you can be recognized for pardons (the main rank is to lay down in addition, how many relatively broken tests are).

    Next, test your code

    If you had never written unit tests before, then, apparently, you simply posted your code on a web server, launched yoga, stalked pardons and tried to get them out of the world. This method of robotics gives rise to a lot of problems.

    First, it’s more tedious, that tedious busyness. The re-verification of the truth is already a folding robot, for it is necessary to be convinced that everything was pressed. And in this process, there is even greater momentum, that one or two moments can be missed.

    In a different way, everything that tries for such a test cannot be re-tried. For such a method, it is already difficult to know the regression. What is regression? Show that you wrote this code and protested against it, corrected all the pardons, as they knew, they posted the code on the site. Potim koristuvach nadislav commentary about new pardons and requests for new functions. You turn to the code, correct the pardons and add new functions. With whom you can blame the situation, if the old pardons appear again, what is called "regression". You'll have to rewrite everything again. І є chance that you do not know your old pardons. Whether it's an hour before the fall, the first time you will guess that the problem of the viklikan is "regression". For an hour of unit testing, you write a test. As soon as the code is modified, you filter it again through the test. If the regression is manifested, then if the test does not pass, and you can easily find out, as part of the code to avenge a pardon. If you don’t know what you changed, then the pardon will be easy to correct.

    Another advantage of unit testing (especially for web development) are those that can easily protest cross-browser confusion. You just need to run tests in different browsers. If there are problems in the browser, you can fix them and run the test again. As a result, you will be convinced that all major browsers are supported, and all stink shards have passed the test.

    How to write unit tests with QUnit

    Otzhe, how to write module tests in QUnit? The first step is to install the middle of the test:

    QUnit test suite

    QUnit test suite

    Code, which is to be tested, to be avenged from the file myProject.js, and tests are placed in myTests.js. To run the tests, you just need to open the HTML file in the browser. Now it's time to write some kind of test.

    Budіvelny block of modular testing є otverdzhennya.

    "The firmness is tse viraz, which predicts the result that turns when your code is victorious. If the forecast is incorrect, then the firmness may be false, which allows you to spread visnovki about the presence of pardons.

    For vikonannya hardness їх it is necessary to place before the test block:

    // test this function function isEven(val) ( return val % 2 === 0; ) test("isEven()", function() ( ok(isEven(0), "Zero is a good number"); ok( isEven(2), "Two - tezh"); ok(isEven(-4), "І negative chotiri - tezh equal number"); ok(!isEven(1), "One - unpaired number"); ok(! isEven(-7), "Yak and negative sіm - unpaired number"); ))

    Here we assign the function isEven, so that the pairing of the number is reversed, and I want to reconsider, so that the function does not rotate the parity values.

    We call the function back to back test() like a block to the test. The first parameter is in a row, which appears in the result. Another parameter is a reversal function, as a way to avenge our assertions. This function will be called once when calling QUnit.

    We wrote five solids, we have є logical. It is logical to confirm that the first parameter has a value true. The other parameter is the reminder value, which is how the result should be displayed.

    The axis of what we take after the test:

    All our assertions have been successfully confirmed, it can be taken into account that the function isEven() pratsyuє so, as ochіkuvalos.

    Let's wonder what will become, if the firmness will be wrong.

    // test this function function isEven(val) ( return val % 2 === 0; ) test("isEven()", function() ( ok(isEven(0), "Zero is a good number"); ok( isEven(2), "Two - tezh"); ok(isEven(-4), "І negative chotiri - tezh equal number"); ok(!isEven(1), "One - unpaired number"); ok(! isEven(-7), "Yak and negative sіm - unpaired number");// Pardon ok(isEven(3), "Three - unpaired number"); ))

    І axis what we take into account in the result of the test:


    Strongly maє pardon, yaku mi started to navmisno. But for your project, if you don’t pass the test, but decide all the statements are correct, then it will be easier to show a pardon.

    Other hardships

    ok() is not the only thing that supports QUnit. Establish other types of hardness, how to manually vicorate when folding tests for your projects:

    Confirmation of the agreement

    Confirmation of the agreement equals() transferring that the first parameter (which is the correct value) is equivalent to the other parameter (which is the correct value). The hardness is already similar to ok() Ale to show insulting meanings - deisne and perebachuvane, which makes it easier to improve the code. So just like i ok(), equals() as the third parameter, you can take notes for viewing.

    So deputy

    Test("assertions", function() ( ok(1 == 1, "one is equivalent to one"); ))


    Slide to win:

    Test("assertions", function() ( equals(1, 1, "one equals one"); ))


    To give respect, which, for example, in a row, shows the transfer of meaning.

    And yet the meaning is not equal:

    Test("assertions", function() ( equals(2, 1, "one equals one"); ))


    Such a record gives more information.

    Validation of the matching of the match operator “==” for rechecking the parameters, this can be done with arrays of objects:

    Test("test", function() ( equals((), (), "pardon, all objects"); equals((a: 1), (a: 1) , "pardon"); equals( , , "pardon, tse rіznі array");equals(, , "pardon");

    For such behaviors, QUnit has a solidified identity.

    Solid identity

    Solid identity same() vikoristova tі w parameters that i equals(), but not only with primitive types, but with arrays and objects. The confirmation from the front buttstock must be re-verified, in order to change the confirmation of the identity:

    Test("test", function() ( same((), (), "pass, objects display the same content"); same((a: 1), (a: 1) , "pass"); same (, , "pass, array and retrieve the same content"); same(, , "pass"); ))

    Respect what same() match operator '===' for matching, so you can manually win for matching special values:

    Test("test", function() ( equals(0, false, "true"); same(0, false, "false"); equals(null, undefined, "true")); same(null, undefined, "false"); ))

    structure

    To disentangle all assertions in one test is a bad idea. Such a test will be important to underestimate and you can get confused in the assessment of the results of yoga. Therefore, it is necessary to structure the test, arranging the hardening of the okre blocks, skin from any of the destinations to the same group of functions.

    You can organize other modules for additional functions module:

    Module("Module A"); test("Test", function() ()); test("Another test", function() ()); module("Module B"); test("Test", function() ()); test("Another test", function() ());


    At the front butt, all the firmness was called out synchronously, so they were beaten one by one. The real world has impersonal asynchronous functions, such as AJAX requests and functions setTimeout()і setInterval(). How can we test this type of function? QUnit has a special type of test called "asynchronous test" and uses it for asynchronous testing:

    We can try to write the test in the most obvious way:

    Test("Asynchronous test", function() ( setTimeout(function() ( ok(true); ), 100) ))


    Looking like this, there are no daily hardships at the test. That's why the hardening was synchronous, but at the moment the call to the function, the test was already over.

    The correct option for testing our butt:

    Test("Asynchronous test", function() ( // Change the test to the "pause" mode stop(); setTimeout(function() ( ok(true); // After the tweet is completed // continue the test start(); ), 100) ))


    We won the function stop() to test the test, and after the test was completed, they ran the test again for an additional function start().

    Wiklik functions stop() right after the weekly function test()є more widely practiced. Therefore, QUnit can be specially shortened: asyncTest(). The front butt can be rewritten at the sight:

    AsyncTest("Asynchronous test", function() ( // The test is automatically put into the "pause" mode setTimeout(function() ( ok(true); // After the feedback is completed // continue the test start(); ), 100) ) )

    Є one moment, over what varto zamylitsya: function setTimeout() Always call your function, and then test another function (for example, AJAX query). How can we be sure that the return function will be called out? As a reversal function, there will be no viklikan, function start() can be lost without a quick call and the entire test is "submitted":


    You can organize the test like this:

    // callback function function ajax(successCallback) ( $.ajax(( url: "server.php", success: successCallback )); ) test("Asynchronous test", function() ( // Running the test and // going to check pardon, because the start() function will not be called after 1 second stop(1000); ajax(function()

    Function stop() timeout value is passed. Now QUnit has removed the prompt: “This is a function start() if there is no vyklikan after the end of the timeout, we will fail the next test.” Now the whole test is not "suspended" and you will see ahead of time, as if it were not so, as it should be.

    Now let's look at a variety of asynchronous functions. Delocate the function start()? It is necessary to place її at the function setTimeout():

    // callback function function ajax(successCallback) ( $.ajax(( url: "server.php", success: successCallback )); ) test("Asynchronous test", function() ( // Run test stop(); ajax (function() ( // ...asynchronous callback)) ajax(function() ( // ...asynchronous callback)) setTimeout(function() ( start(); ), 2000);

    Before proceeding with the test, the timeout value may be sufficient for cycling both functions. If one of the functions will not be a viklican, how will you appoint it, how will it be yourself? For whom is the function expect():

    // Code function function ajax(successCallback) ( $.ajax(( url: "server.php", success: successCallback )); ) test("Asynchronous test", function() ( // Run the test stop(); / / Note to QUnit that it is worth noting that the expect(3); ) ( start(); ), 2000); ))

    We are passed to the function expect() kіlkіst firm, yakі planuєtsya vikonati. As one of the strongholds will not be a vikonan, you take care of those that go wrong, as planned.

    Є short note for wiki expect(): it is necessary to pass the amount of hardening, which are planned, as another parameter test() or asyncTest():

    // callback function function ajax(successCallback) ( $.ajax(( url: "server.php", success: successCallback )); ) // Note to QUnit that we obviously hit 3 test("asynchronous test", 3, function() ( // Run the test stop(); ajax(function() ( ok(true); )) ajax(function() ( ok(true); ok(true); )) setTimeout(function() ( start (); ), 2000); ))

    Visnovok

    At this school, we have brought everything that is necessary for the cob of work with QUnit. Modular testing is a magical method for re-testing code before it is tested. As if you hadn’t won the annual tests before, it’s time to tell.

    On the example of a simple calculator on Node.js. Testing for help with the Mocha framework.

    What can our program include:

    • Add, see, divide and multiply, be it two numbers;
    • Show advance and complete the work, as it was entered earlier in the same number;
    • Also may be the interface command line, shob kіntsevy spozhivach instantly speed up the program.

    What do we need:

    • Node.js and npm;
    • Knowledge of JavaScript: syntax and code structure, types of data, mathematical operations and smart language.

    With the aims of expanding, you can proceed to setting up the middle for testing and expanding.

    Let's go Wednesday

    Shards of mimic Node.js, you need to create local honing for files and fallows.

    Create new folder calc. From the command line, go to the tsієї directory and create a new project with the npm init command, how to create new file package.json for our program.

    You are prompted to enter the package name, version, description and other information about the package. You can enter your name calc.js and farther emboss Enter for nadannya value for zamovchuvannyam. If you get to the test command, enter mocha - the whole framework for testing, which we will win:

    test command: mocha

    After entering all the information, the script will create a file package.json, which looks something like this:

    ( "name": "calc.js", "version": "1.0.0", "description": "Simple Node.js calculator", "main": "index.js", "scripts": ( " test": "mocha" ), "author": "", "license": "ISC" )

    The last step at this stage is the installation of Mocha. Enter the next command to install:

    npm install --save-dev mocha

    After zastosuvannya tsієї command z'appear folder node_modules, file package-lock.json, while the file package.json to appear next rows:

    "devDependencies": ( "mocha": "^4.0.1" )

    Create file test.js. We are speeding up to be introduced to Node.js with a module assert, in order to reverse the validity of the equality true and true. So it’s more correct, the test can pass successfully:

    Const assert = require("assert"); it("may turn true", () => ( assert.equal(true, true); ));

    Now run the test from the command line:

    $ npm test > mocha ✓ turn true 1 passing (8ms)

    The test passed as if it was cleared up, so the middle was finished. View from test.js everything, krim row const assert = require ("assert"); .

    We'll tweet the file test.js by stretching the process of creating programs. Create two more files: operations.js for arithmetic and validation functions and calc.js for the program itself. We vikoristovuemo so richly filed, so that the stench did not become too long and foldable. The axis of our current list of files:

    • calc.js;
    • node_modules;
    • operations.js;
    • package-lock.json;
    • package.json;
    • test.js;

    Let's finish the first reference test for our program.

    Dodaemo mathematical operations

    First of all, our program is guilty of adding, seeing, dividing and multiplying, be it two numbers. Also, skin operations from these operations can create a functional function.

    Let's start with the folding. Let's write a test, for which the sum of two numbers is uniquely calculated. In the code below, we check that the cost is 1 and 3 for the additional function add() 4:

    Const assert = require("assert"); it("correctly know the sum of 1 and 3", () => ( assert.equal(add(1, 3), 4); ));

    After I run the test for the help of the npm test command, I do this:

    > mocha 0 passing (9ms) 1 failing 1) know sum 1 and 3 correctly: ReferenceError: add is not defined at Context.it (test.js:5:16) npm ERR! test failed. Look for more details.

    Test failed with referenceError: add is not defined . We test the add() function, as there is no other way, so such a result is quite clear.

    Let's create the add() function for the file operations.js:

    Const add = (x, y) => (+x) + (+y);

    This function takes two arguments x and y and rotates the sum. You might remember that we write (+x) + (+y) and not x + y . We use the unary operator to reduce the argument to a number, on the other hand, so that the introduction will be in a row.

    Note Here we add ES6 arrow function and implicit rotation.

    We use Node.js and split the code into anonymous files, it is necessary to speed up module.exports for export code:

    Const add = (x, y) => (+x) + (+y); module.exports = (add)

    Top of the file test.js we import code z operations.js for the help of require(). To win the function over by changing operations , you need to remember add() to operations.add() :

    Const operations = require("./operations.js"); const assert = require("assert"); it("correctly know the sum of 1 and 3", () => ( assert.equal(operations.add(1, 3), 4); ));

    Let's run the test:

    $ npm test > mocha ✓ correctly know sum 1 and 3 1 passing (8ms)

    Now we have a function that works, and the tests pass successfully. The rest of the functions of other operations work in a similar order, adding tests for subtract() , multiply() and divide() are not difficult:

    It("correctly know the sum of 1 and 3", () => ( assert.equal(operations.add(1, 3), 4); )); it("correctly know the sum -1 і -1", () => ( assert.equal(operations.add(-1, -1), -2); )); it("correctly know the difference 33 і 3", () => ( assert.equal(operations.subtract(33, 3), 30); )); it("correctly know tvir 12 and 12", () => ( assert.equal(operations.multiply(12, 12), 144); )); it("it is correct to know privately 10 and 2", () => ( assert.equal(operations.divide(10, 2), 5); ));

    Now we create and export all functions in test.js:

    Const add = (x, y) => (+x) + (+y); const subtract = (x, y) => (+x) - (+y); const multiply = (x, y) => (+x) * (+y); const divide = (x, y) => (+x) / (+y); module.exports = ( add, subtract, multiply, divide, )

    І launch new tests:

    $ npm test > mocha ✓ correctly know the amount 1 and 3 ✓ correctly know the amount -1 and -1 ✓ correctly knows the price 33 and 3 ✓ correctly knows the tvіr 12 and 12 ✓ correctly knows the private 10 and 2 5 passing (8ms)

    All tests pass successfully, so now we can be sure that the main functions of our program work correctly. Now you can do additional validation.

    We add validation

    At the moment, if you enter the correct number and choose the operation you need, everything works fine. However, how to get on, how to try to know the sum of the number of that row? The program will try the vikonati operation, but through those that check the numbers, turn NaN .

    The deputy turned around like an unreasonable meaning, the time has come to vikonate another task - work in such a way as to show the addition of advance and complete your work, so that the introduction of the argument is not a number.

    It is necessary to write a function on the back of the head, as we can check, chi є introduced by the number chi nі. The addendum can only be practiced with numbers, so three situations can be summarized:

    1. Offenses introduced - numbers.
    2. One entry is a number, and the other is a row.
    3. Offending introduction - rows.
    it("remind about the pardon when the number is changed", () => ( assert.equal(operations.validateNumbers("sammy", 5), false); )); it("remind about the pardon when two rows are replaced", () => ( assert.equal(operations.validateNumbers("sammy", "sammy"), false); )); it("success when there are no more than two numbers", () => ( assert.equal(operations.validateNumbers(5, 5), true); ));

    The validateNumbers() function overrides both parameters. The isNaN() function checks if the parameter is not a number, and if not, then it turns false . Otherwise, it will turn true, which means a successful validation.

    Const validateNumbers = (x, y) => ( if (isNaN(x) && isNaN(y)) ( return false; ) return true; )

    Don't forget to add validateNumbers to module.exports in the end file. Now you can run new tests:

    $ npm test 1) remember about pardon when multiple rows replace numbers ✓ report about pardon when multiple rows replace numbers ✓ success when multiple strings replace numbers 7 passing (12ms) 1 failing 1) report about pardon when multiple rows replace numbers ✓ successful: true: Assertion Error: == false + expected - actual -true + false

    Two tests passed, but one failed. The re-verification for the introduction of two numbers was successful, as well as the re-verification for the introduction of two rows. What can not be said about the re-verification on the introduction of a row of that number.

    If you take a look at our function again, you can note that resentment The parameter can be set to NaN so that the function evaluates to false. If we want to achieve the same effect, if we want one of the parameters to be NaN, we need to replace && with || :

    Const validateNumbers = (x, y) => ( if (isNaN(x) || isNaN(y)) ( return false; ) return true; )

    After these changes, run npm test again, then all tests will pass successfully:

    ✓ remind about the pardon in case of a victorious row the replacement of the number ✓ tell about the pardon in the case of a victorious two rows the replacement of numbers ✓ success in the case of a victorious two numbers 8 passing (9ms)

    We protested all the functionality of our program. Functions successfully win mathematical operations and revise the input. The final stage is the creation of the coristuvach interface.

    We create an interface

    You may need functions already, but for the time being, you can’t speed up with them. Therefore, we need an interface. For our program, we create a command line interface.

    At the moment the file calc.js may be empty. Here and save our program. You need to import the functions from the start operations.js:

    Const operations = require("./operations.js");

    The vicorist interface itself is used in the Node.js Readline CLI module:

    Const readline = require("readline");

    After importing everything that is necessary, you can proceed before the program is created. To create an interface, we will tweak readline, accessible via the rl change:

    Const rl = readline.createInterface(( input: process.stdin, output: process.stdout ));

    First, that the koristuvach is guilty of bachiti after the launch of the program, - it is vitally reminded of that instruction how to win. For which we speed console.log() :

    Console.log(` Calc.js You have entered the calculator on Node.js! Version: 1.0.0. Quiz: koristuvach is required to enter two numbers, and then choose what to work with them. `);

    First, let's take a look at the calculator's functions themselves, and see if console.log() works as required. Mi zrobimo so that the program brought up prompts and completed the work. For some, add a quick click to the rl.close() method.

    To run the program, enter node and file name:

    $ node calc.js Calc.js You've got the Node.js calculator! Version: 1.0.0. Vocabulary: the koristuvach is obliged to enter two numbers, and then choose what to work with them.

    The program to display vital notifications will complete its work. Now it is necessary to add the introduction of a coristuvach. It’s necessary to step forward: choose two numbers and one operation. The input skin will be requested by the rl.question() method:

    Rl.question("Enter a first number: ", (x) => ( rl.question("Enter a different number: ", (y) => ( rl.question(` Select one of the upcoming operations) ) (-) Multiple (*) Sub (/) Your choice: `, (choice) => ( // rl.close(); )); )); ));

    Changing x hopes for the first number, y - another, and choice - the operation is chosen. Now our program is asking for input, but not to do anything from taking the money.

    After the third introduction, it is necessary to check if only the numbers were entered. For which speed, use the validateNumbers() function. For the help of the operator, we are NOT going to check if the numbers were entered, and if not, we will complete the robot program:

    If (!operations.validateNumbers(x, y)) ( console.log("You can only enter numbers! Please, restart the program."); )

    If everything is entered correctly, then it is now necessary to run the second operation method, the previous creations. To process as many possible options as you choose, we speed it up with the switch virusase and display the result of the operation. If an unknown operation is selected, the default block will be displayed, which will remind you to repeat the test:

    If (!operations.validateNumbers(x, y)) ( console.log("You can only enter numbers! Please, restart the program."); ) else ( switch (choice) ( case "1": console.log(` Amount $(x) and $(y) cost $(operations.add(x, y)).`), break, case "2": console.log(`Retail $(x) and $(y) cost $ ( operations.subtract(x, y)).`); break; case "4": console.log(`Private $(x) and $(y) private $(operations.divide(x, y)).` ); break; restart the program and select a number from 1 to 4."); break; ) )

    Note The console.log() functions have wildcard strings that allow multiple strings.

    /** * A simple Node.js calculator, a kind of calculator app that uses * the command-line interface of Readline. */ const operations = require("./operations.js"); const readline = require("readline"); // Victory readline to create an interface const rl = readline.createInterface((input: process.stdin, output: process.stdout)); console.log(` Calc.js You opened the calculator in Node.js! Version: 1.0.0. Quiz: you have to enter two numbers, then choose what to work with them. `); rl.question("Enter a first number: ", (x) => ( rl.question("Enter a different number: ", (y) => ( rl.question(` Select one of the upcoming operations) ) (-) Multiplication (*) Submitted (/) Your choice: `, (choice) => ( if (!operations.validateNumbers(x, y)) ( console.log("Only numbers can be entered! Please, restart program). "); ) else ( switch (choice) ( case "1": console.log(`Amount $(x) and $(y) total $(operations.add(x, y)).`); break; case "2": console.log(`Retail $(x) and $(y) cost $(operations.subtract(x, y)).`); x) and $(y) one $(operations. multiply(x, y)).`), break; divide(x, y)).`); break; ;));

    Now our program is ready. Let's reconsider yoga robot at last. Enter 999 and 1 and select the operation to be performed:

    $ node calc.js Enter first number: 999 Enter another number: 1 Your choice: 2 Cost 999 and 1 cost 998.

    The program successfully completed its work, giving the correct result. Well, you wrote a simple calculator using Node.js and learned the basics of TDD development.

    © 2022 androidas.ru - All about Android