1. The document discusses various topics related to testing JavaScript code including unit testing, test-driven development (TDD), the QUnit testing framework, mocking AJAX requests, and testing user actions.
2. Key points about QUnit include that it is a JavaScript unit testing framework used to test jQuery, jQuery UI, and other code. It allows writing tests, assertions, handling asynchronous code, and grouping tests into modules.
3. Mocking AJAX requests is discussed as a way to test code that relies on asynchronous requests without needing a server. The Mockjax library allows intercepting and simulating AJAX responses.
JAVASCRIPT Test Driven Development & JasmineAnup Singh
The document discusses test driven development and the JavaScript testing framework Jasmine. It provides an overview of unit testing and test driven development processes. It then describes key aspects of Jasmine such as describing test suites and specifications, using matchers and assertions to test expectations, setting up tests using beforeEach and tearing them down using afterEach, creating custom matchers, spying on functions, and handling asynchronous tests. The document aims to introduce readers to testing JavaScript code using the Jasmine framework.
The document discusses unit testing and test-driven development. It introduces the QUnit JavaScript testing framework, describing how to write tests and assertions using its API. Key aspects covered include setting up QUnit, the test and assert functions, asynchronous testing, grouping tests into modules, and integrating automated testing with Node and Grunt.
Stop Making Excuses and Start Testing Your JavaScriptRyan Anklam
The document provides tips for adding testing to JavaScript projects. It recommends choosing a testing environment and dialect, then setting up the tests by installing dependencies and configuring files. Common issues like testing asynchronous code and methods that call other methods can be addressed with spies, stubs, mocks and promises. Tests should focus on isolated units of code and avoid direct DOM manipulation when possible. Automating testing through build tools like Grunt and Testem helps to easily run and watch tests. Overall, the document emphasizes making testing easy by writing maintainable, modular code and setting up automation.
JMockit is a Java mocking framework that provides tools for isolating code dependencies during unit testing. It uses bytecode instrumentation to remap classes at runtime, allowing final classes and static methods to be mocked. Expectations define mock object behavior, and verifications ensure mocks are used as expected. JMockit provides a more powerful and flexible mocking approach than alternatives like Mockito through its instrumentation and expectations/verifications APIs.
This document provides an overview of JMockit, a mocking framework for unit testing Java code. It discusses how to install JMockit, use annotations like @Mocked and @Injectable to mock classes and instances, set up expectations to define mocked method return values, partially mock classes by mocking specific methods, mock constructors, and verify mocked method calls were made using verifications. The document also explains how to use JMockit's code coverage reporting and addresses common scenarios for when to use expectations, mockups, constructor mocking, and verifications.
This document provides an introduction to JUnit and Mockito for testing Java code. It discusses how to set up JUnit tests with annotations like @Before, @After, and @Test. It also covers using JUnit assertions and test suites. For Mockito, the document discusses how to create and use mock objects to stub behavior and verify interactions. It provides examples of argument matchers and consecutive stubbing in Mockito.
Mockito vs JMockit, battle of the mocking frameworksEndranNL
(Original keynote slides can be found at https://github.com/Endran/PublicSlides)
For years the industry standard of mocking on the JVM has been Mockito. Mockito is a wonderful library that really speeds up your testing by allowing you to create mocks in a very simple way. That being said, it does have its drawbacks, for which different strategies need to be deployed to keep your code testable. The main drawbacks are statics and finals. Final classes cannot be mocked, nor final methods, and also static methods are a no-go. To work with these type of things we need to wrap it, and copy the signature in a non final, non static way.
I have a great adversity against statics, I've devoted an entire post about it, in short; It hides dependencies and brings so little convenience at the costs of its drawbacks. Finals on the other hand have purpose, it helps messaging the goal of a class or method. Java is one of the few languages where classes and methods are open/virtual by default and have to be closed/final by explicit action. In (for example) Kotlin, everything is final by default, if you do not want something to be final, you should use the open keyword.
No matter if you follow the principle of making things final, static or not, if you are using Mockito the decision has been made. This mocking framework demands that everything is non-final, demands that everything is designed to be extended, since it might need to be mocked away. We should be able to improve upon this, and by the name of this post, you should be able to guess which framework will save the day. JMockit will help us with our impediments, and will give some other nifty benefits as well!
JAVASCRIPT Test Driven Development & JasmineAnup Singh
The document discusses test driven development and the JavaScript testing framework Jasmine. It provides an overview of unit testing and test driven development processes. It then describes key aspects of Jasmine such as describing test suites and specifications, using matchers and assertions to test expectations, setting up tests using beforeEach and tearing them down using afterEach, creating custom matchers, spying on functions, and handling asynchronous tests. The document aims to introduce readers to testing JavaScript code using the Jasmine framework.
The document discusses unit testing and test-driven development. It introduces the QUnit JavaScript testing framework, describing how to write tests and assertions using its API. Key aspects covered include setting up QUnit, the test and assert functions, asynchronous testing, grouping tests into modules, and integrating automated testing with Node and Grunt.
Stop Making Excuses and Start Testing Your JavaScriptRyan Anklam
The document provides tips for adding testing to JavaScript projects. It recommends choosing a testing environment and dialect, then setting up the tests by installing dependencies and configuring files. Common issues like testing asynchronous code and methods that call other methods can be addressed with spies, stubs, mocks and promises. Tests should focus on isolated units of code and avoid direct DOM manipulation when possible. Automating testing through build tools like Grunt and Testem helps to easily run and watch tests. Overall, the document emphasizes making testing easy by writing maintainable, modular code and setting up automation.
JMockit is a Java mocking framework that provides tools for isolating code dependencies during unit testing. It uses bytecode instrumentation to remap classes at runtime, allowing final classes and static methods to be mocked. Expectations define mock object behavior, and verifications ensure mocks are used as expected. JMockit provides a more powerful and flexible mocking approach than alternatives like Mockito through its instrumentation and expectations/verifications APIs.
This document provides an overview of JMockit, a mocking framework for unit testing Java code. It discusses how to install JMockit, use annotations like @Mocked and @Injectable to mock classes and instances, set up expectations to define mocked method return values, partially mock classes by mocking specific methods, mock constructors, and verify mocked method calls were made using verifications. The document also explains how to use JMockit's code coverage reporting and addresses common scenarios for when to use expectations, mockups, constructor mocking, and verifications.
This document provides an introduction to JUnit and Mockito for testing Java code. It discusses how to set up JUnit tests with annotations like @Before, @After, and @Test. It also covers using JUnit assertions and test suites. For Mockito, the document discusses how to create and use mock objects to stub behavior and verify interactions. It provides examples of argument matchers and consecutive stubbing in Mockito.
Mockito vs JMockit, battle of the mocking frameworksEndranNL
(Original keynote slides can be found at https://github.com/Endran/PublicSlides)
For years the industry standard of mocking on the JVM has been Mockito. Mockito is a wonderful library that really speeds up your testing by allowing you to create mocks in a very simple way. That being said, it does have its drawbacks, for which different strategies need to be deployed to keep your code testable. The main drawbacks are statics and finals. Final classes cannot be mocked, nor final methods, and also static methods are a no-go. To work with these type of things we need to wrap it, and copy the signature in a non final, non static way.
I have a great adversity against statics, I've devoted an entire post about it, in short; It hides dependencies and brings so little convenience at the costs of its drawbacks. Finals on the other hand have purpose, it helps messaging the goal of a class or method. Java is one of the few languages where classes and methods are open/virtual by default and have to be closed/final by explicit action. In (for example) Kotlin, everything is final by default, if you do not want something to be final, you should use the open keyword.
No matter if you follow the principle of making things final, static or not, if you are using Mockito the decision has been made. This mocking framework demands that everything is non-final, demands that everything is designed to be extended, since it might need to be mocked away. We should be able to improve upon this, and by the name of this post, you should be able to guess which framework will save the day. JMockit will help us with our impediments, and will give some other nifty benefits as well!
Unit testing involves writing code to test individual units or components of an application to ensure they operate as intended. A unit test targets a specific function or class and ensures the code works correctly. A test suite is a collection of test cases that test a module. Frameworks like JUnit simplify the unit testing process and allow for test automation. JUnit tests are created in the same project structure with a "Test" suffix and use annotations to define test cases and suites. Tests can then be run and results analyzed to measure code coverage.
The document discusses unit testing frameworks for Objective-C and iOS development. It recommends the OCUnit framework for new Xcode projects with few test cases, and the GHUnit framework for projects needing more advanced testing capabilities. It provides an example of how to set up and write a basic unit test using the OCUnit framework.
A talk about unit testing for iOS apps. Part rambling introduction to test driven development, part examples of certain types of tests for iOS, and a brief mention of writing your tests using Kiwi.
This document provides an overview of GoogleMock, a mocking framework for C++. It defines what a mock object is and why they are useful for testing. GoogleMock allows specifying expectations for mock method calls, including how many times a method will be called and what it will return. It provides matchers to check arguments and actions to define return values or behaviors. The document demonstrates how to write mock classes, set expectations, and use mocks in tests to verify code interactions and behavior.
JUnit is the de facto standard in Java testing. Yet many advanced JUnit features are little known and poorly understood. This session reviews some lesser-known features of JUnit, along with a few associated libraries, that can make your unit tests more powerful, expressive, and fun. The session is intended for Java developers, lead developers, and architects trying to introduce good testing practices into their teams.
The document discusses JUnit 5, the next generation of the JUnit testing framework for Java. Key aspects include a new programming model using extensions, support for Java 8 features, and ways to migrate from earlier JUnit versions. The new framework consists of the JUnit Platform launcher, the JUnit Jupiter API for writing tests, and the JUnit Vintage engine for running JUnit 3 and 4 tests.
Unit testing with JUnit can be done using JUnit 3.x or 4.x frameworks. Key aspects include writing test cases as Java classes that extend TestCase and contain test methods starting with "test", using assertion methods like assertTrue and assertEquals to validate outcomes, and running tests from Eclipse. JUnit 4.x introduced annotations like @Before, @Test, and @After to respectively set up objects before each test, identify test methods, and tear down objects after tests.
This document summarizes advanced features in JUnit, including:
1. It discusses features like @ClassRule and @Rule in JUnit advanced, which allow implementing custom rules for tests.
2. It mentions experimental features in JUnit like the Enclosed runner, which allows grouping tests into logical blocks.
3. It provides links to resources on Mockito, a mocking framework, comparing it to other mocking frameworks like EasyMock and JMock. Mockito allows stubbing and verifying method calls on mock objects.
Test-driven development (TDD) involves writing unit tests before writing application code. TDD promotes writing high-quality code and prevents regressions. It follows a "red-green-refactor" process of writing a failing test, making it pass by writing minimal code, and refactoring the code. Unit test frameworks allow automating tests and isolating code dependencies using techniques like stubs, fakes, and mocks. Tests should be organized into test classes and follow a lifecycle of setup, execution, and teardown.
Test driven development - JUnit basics and best practicesNarendra Pathai
A presentation covering all the basics of Software Unit testing using JUnit framework. A lot of best practices, myths misconceptions are covered. Naming conventions for test methods and fundamental requirements for doing sustainable Junit testing.
The document discusses unit testing methods like stubbing and mocking. It introduces Mockito, a mocking framework that makes creating mock objects easier. Mockito allows generating mock objects, setting mock behavior using matchers, and verifying mock interactions. It also discusses partial mocking with spies and cautions against over-specifying mock behavior, which can lead to brittle tests. PowerMock is introduced as an extension to Mockito that enables mocking additional constructs like static methods.
This document provides an introduction to using the Google Test framework for unit testing C++ code. It begins with an example of a simple test for a function called calc_isect. It then demonstrates how to add assertions to tests, use test fixtures to reduce duplicated setup code, and generate parameterized tests. The document also covers best practices for test organization, installing and using Google Test, and some key features like XML output and selecting subsets of tests. Overall, the document serves as a tutorial for getting started with the Google Test framework for writing and running unit tests in C++ projects.
Unit testing with JUnit focuses on testing individual units of source code using JUnit. Key aspects covered include:
- Unit testing tests the smallest testable parts of code, while integration testing tests groups of code modules and system testing tests complete integrated systems.
- Tests in JUnit are implemented as public void testX() methods that call methods under test and assert expected outcomes.
- A test suite assembles individual test methods using reflection and executes the suite to automatically run all tests.
- Best practices include writing tests before code, testing all code that could break, and running tests frequently for rapid feedback.
V1.0
How often do you get a bug report that you can’t reproduce?
How often do you struggle to find the source of the bug in your code?
How can you streamline the testing process and make sure you don’t repeat the same bugs?
With Visual Studio 2010 & Team Foundation Server (TFS) 2010 there are a lot of new features for testers and developers that will solve these problems.
In this session you will learn how to: automate more, reproduce bugs easier, maintain your tests and configuration and discover problems sooner.
from Peter Gfader
JUnit is a unit testing framework for Java that allows developers to write and run repeatable automated tests of Java code. Key aspects of JUnit include:
1. Tests are written by creating test classes that extend JUnit's TestCase class and contain test methods with names beginning with "test".
2. Tests use JUnit's assert methods like assertEquals to make assertions and determine whether the test passed or failed.
3. Annotations like @Before and @After allow setting up fixtures that run before and after each test.
4. The TestRunner class collects and runs all test cases and reports results.
5. Tests can be organized into test suites to group related tests and control execution
JUnit is a unit testing framework for Java programming language. It was originally written by Kent Beck and Erich Gamma. Some key points:
- JUnit was one of the first unit testing frameworks for Java and has become the de facto standard.
- It allows writing and running repeatable tests to help find and prevent bugs. Tests are written in plain Java classes and methods.
- JUnit provides annotations like @Test, @Before, @After to identify test methods and set up/tear down methods.
- It includes assertions for validations and will report failures immediately. Tests can be organized into test suites.
Mockito is a mocking framework for Java that allows developers to focus tests on interactions between objects rather than states. It provides test doubles like mocks and spies to simulate dependencies and verify expected interactions. Mockito allows mocking method calls and configuring return values or exceptions to test different scenarios. It provides default values for unstubbed calls to avoid overspecifying tests.
The document discusses unit testing in Grails using the Spock testing framework. It covers the basics of unit testing including goals, advantages, and challenges. It then provides an overview of Spock and examples of writing unit tests in Spock including mocking methods, domains, configurations, and dependencies. The document also discusses how to write unit tests for controllers and integration tests in Grails using Spock.
This document discusses different types of automated testing in Joomla including unit tests, integration tests, system/browser tests, JavaScript tests, and code style tests. It provides examples of each type of test and how they benefit developers. It also explains how these different tests are implemented in the Joomla codebase and can be run locally for developers to validate their code changes before creation a pull request. The goal of these automated tests is to deliver a more reliable and bug-free application by testing each change and to welcome new volunteers to contribute to expanding test coverage.
This document discusses unit testing, including why testing is important, how to begin unit testing, asynchronous testing, and performance testing. It provides an overview of using XCTest to write unit tests in Xcode, including test targets, running and viewing test results. It covers writing asynchronous tests using expectations and measuring performance using the measureBlock method. The document recommends setting baselines and standard deviations for performance tests and provides references for learning more about unit and UI testing.
Unit testing involves writing code to test individual units or components of an application to ensure they operate as intended. A unit test targets a specific function or class and ensures the code works correctly. A test suite is a collection of test cases that test a module. Frameworks like JUnit simplify the unit testing process and allow for test automation. JUnit tests are created in the same project structure with a "Test" suffix and use annotations to define test cases and suites. Tests can then be run and results analyzed to measure code coverage.
The document discusses unit testing frameworks for Objective-C and iOS development. It recommends the OCUnit framework for new Xcode projects with few test cases, and the GHUnit framework for projects needing more advanced testing capabilities. It provides an example of how to set up and write a basic unit test using the OCUnit framework.
A talk about unit testing for iOS apps. Part rambling introduction to test driven development, part examples of certain types of tests for iOS, and a brief mention of writing your tests using Kiwi.
This document provides an overview of GoogleMock, a mocking framework for C++. It defines what a mock object is and why they are useful for testing. GoogleMock allows specifying expectations for mock method calls, including how many times a method will be called and what it will return. It provides matchers to check arguments and actions to define return values or behaviors. The document demonstrates how to write mock classes, set expectations, and use mocks in tests to verify code interactions and behavior.
JUnit is the de facto standard in Java testing. Yet many advanced JUnit features are little known and poorly understood. This session reviews some lesser-known features of JUnit, along with a few associated libraries, that can make your unit tests more powerful, expressive, and fun. The session is intended for Java developers, lead developers, and architects trying to introduce good testing practices into their teams.
The document discusses JUnit 5, the next generation of the JUnit testing framework for Java. Key aspects include a new programming model using extensions, support for Java 8 features, and ways to migrate from earlier JUnit versions. The new framework consists of the JUnit Platform launcher, the JUnit Jupiter API for writing tests, and the JUnit Vintage engine for running JUnit 3 and 4 tests.
Unit testing with JUnit can be done using JUnit 3.x or 4.x frameworks. Key aspects include writing test cases as Java classes that extend TestCase and contain test methods starting with "test", using assertion methods like assertTrue and assertEquals to validate outcomes, and running tests from Eclipse. JUnit 4.x introduced annotations like @Before, @Test, and @After to respectively set up objects before each test, identify test methods, and tear down objects after tests.
This document summarizes advanced features in JUnit, including:
1. It discusses features like @ClassRule and @Rule in JUnit advanced, which allow implementing custom rules for tests.
2. It mentions experimental features in JUnit like the Enclosed runner, which allows grouping tests into logical blocks.
3. It provides links to resources on Mockito, a mocking framework, comparing it to other mocking frameworks like EasyMock and JMock. Mockito allows stubbing and verifying method calls on mock objects.
Test-driven development (TDD) involves writing unit tests before writing application code. TDD promotes writing high-quality code and prevents regressions. It follows a "red-green-refactor" process of writing a failing test, making it pass by writing minimal code, and refactoring the code. Unit test frameworks allow automating tests and isolating code dependencies using techniques like stubs, fakes, and mocks. Tests should be organized into test classes and follow a lifecycle of setup, execution, and teardown.
Test driven development - JUnit basics and best practicesNarendra Pathai
A presentation covering all the basics of Software Unit testing using JUnit framework. A lot of best practices, myths misconceptions are covered. Naming conventions for test methods and fundamental requirements for doing sustainable Junit testing.
The document discusses unit testing methods like stubbing and mocking. It introduces Mockito, a mocking framework that makes creating mock objects easier. Mockito allows generating mock objects, setting mock behavior using matchers, and verifying mock interactions. It also discusses partial mocking with spies and cautions against over-specifying mock behavior, which can lead to brittle tests. PowerMock is introduced as an extension to Mockito that enables mocking additional constructs like static methods.
This document provides an introduction to using the Google Test framework for unit testing C++ code. It begins with an example of a simple test for a function called calc_isect. It then demonstrates how to add assertions to tests, use test fixtures to reduce duplicated setup code, and generate parameterized tests. The document also covers best practices for test organization, installing and using Google Test, and some key features like XML output and selecting subsets of tests. Overall, the document serves as a tutorial for getting started with the Google Test framework for writing and running unit tests in C++ projects.
Unit testing with JUnit focuses on testing individual units of source code using JUnit. Key aspects covered include:
- Unit testing tests the smallest testable parts of code, while integration testing tests groups of code modules and system testing tests complete integrated systems.
- Tests in JUnit are implemented as public void testX() methods that call methods under test and assert expected outcomes.
- A test suite assembles individual test methods using reflection and executes the suite to automatically run all tests.
- Best practices include writing tests before code, testing all code that could break, and running tests frequently for rapid feedback.
V1.0
How often do you get a bug report that you can’t reproduce?
How often do you struggle to find the source of the bug in your code?
How can you streamline the testing process and make sure you don’t repeat the same bugs?
With Visual Studio 2010 & Team Foundation Server (TFS) 2010 there are a lot of new features for testers and developers that will solve these problems.
In this session you will learn how to: automate more, reproduce bugs easier, maintain your tests and configuration and discover problems sooner.
from Peter Gfader
JUnit is a unit testing framework for Java that allows developers to write and run repeatable automated tests of Java code. Key aspects of JUnit include:
1. Tests are written by creating test classes that extend JUnit's TestCase class and contain test methods with names beginning with "test".
2. Tests use JUnit's assert methods like assertEquals to make assertions and determine whether the test passed or failed.
3. Annotations like @Before and @After allow setting up fixtures that run before and after each test.
4. The TestRunner class collects and runs all test cases and reports results.
5. Tests can be organized into test suites to group related tests and control execution
JUnit is a unit testing framework for Java programming language. It was originally written by Kent Beck and Erich Gamma. Some key points:
- JUnit was one of the first unit testing frameworks for Java and has become the de facto standard.
- It allows writing and running repeatable tests to help find and prevent bugs. Tests are written in plain Java classes and methods.
- JUnit provides annotations like @Test, @Before, @After to identify test methods and set up/tear down methods.
- It includes assertions for validations and will report failures immediately. Tests can be organized into test suites.
Mockito is a mocking framework for Java that allows developers to focus tests on interactions between objects rather than states. It provides test doubles like mocks and spies to simulate dependencies and verify expected interactions. Mockito allows mocking method calls and configuring return values or exceptions to test different scenarios. It provides default values for unstubbed calls to avoid overspecifying tests.
The document discusses unit testing in Grails using the Spock testing framework. It covers the basics of unit testing including goals, advantages, and challenges. It then provides an overview of Spock and examples of writing unit tests in Spock including mocking methods, domains, configurations, and dependencies. The document also discusses how to write unit tests for controllers and integration tests in Grails using Spock.
This document discusses different types of automated testing in Joomla including unit tests, integration tests, system/browser tests, JavaScript tests, and code style tests. It provides examples of each type of test and how they benefit developers. It also explains how these different tests are implemented in the Joomla codebase and can be run locally for developers to validate their code changes before creation a pull request. The goal of these automated tests is to deliver a more reliable and bug-free application by testing each change and to welcome new volunteers to contribute to expanding test coverage.
This document discusses unit testing, including why testing is important, how to begin unit testing, asynchronous testing, and performance testing. It provides an overview of using XCTest to write unit tests in Xcode, including test targets, running and viewing test results. It covers writing asynchronous tests using expectations and measuring performance using the measureBlock method. The document recommends setting baselines and standard deviations for performance tests and provides references for learning more about unit and UI testing.
- Testing JavaScript code helps ensure quality and allows for refactoring and code handovers. Unit, integration, and functional testing methodologies were discussed.
- Siesta was introduced as a JavaScript testing tool that supports unit and functional testing for Ext JS and Sencha Touch. It allows simulating user interactions and verifying results.
- Writing testable code through separation of concerns, avoiding direct DOM manipulation, and supporting dependency injection were recommended to facilitate automated testing. Continuous integration was also recommended for running tests regularly.
This document provides an overview of unit testing and mocking frameworks. It discusses why we unit test and mock, defines common mocking terminology like mocks, stubs and dummies. It then provides an introduction to the Mockito mocking framework, including its syntax and limitations. Examples are provided to demonstrate mocking with Mockito for a user report generation system.
Unit Testing: The Whys, Whens and Hows discusses unit testing definitions, benefits, and best practices. It covers:
- Defining what constitutes a unit test and different testing styles. Unit tests should be written by developers, run fast, be deterministic, and not integrate multiple areas of code.
- Benefits of unit testing include better code quality, a safety net for refactoring, documentation of functionality, and preventing code from becoming untestable.
- Characteristics of good unit tests like being functionally correct, running independently, running fast, and adding new tests for bugs fixed. Good code is more unit testable through interfaces, contracts, and low dependencies.
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentAll Things Open
The document provides an overview of test-driven development (TDD) principles and how to implement testing for front-end development. It discusses the benefits of TDD, such as avoiding bad designs and preventing regressions. It also addresses common challenges with TDD, like slowing initial velocity and ignored tests over time. The document then covers different levels of testing, including unit tests, integration tests, and functional/end-to-end tests using the testing pyramid as a framework. It provides examples of writing tests for pure and impure functions using the Jest testing framework. Finally, it discusses functional testing using Cucumber.js behavior-driven development.
This workshop is about testing the right way. Get a clear view on how to test your code in an efficient and useful way!
This first testing-related workshop is about all aspects of unit testing. Integration testing and TDD will have their own dedicated workshops.
Building unit tests correctly with visual studio 2013Dror Helper
Unit testing is now considered a mainstream practice, but that does not mean it is as common, pervasive or as well understood as it could or should be. Many programmers struggle with the quality of their tests and with the focus of their code. In this session we’ll learn how to write good unit testing code.
The document provides an overview of unit testing concepts and best practices. It discusses what unit testing is, why it's useful, and common terminology like test-driven development, stubs, spies, mocks and fixtures. It also covers unit testing tools and libraries, specifics of unit testing JavaScript code, and best practices like writing tests that are fast, isolated, consistent and self-descriptive.
В ходе доклада мы обсудим такие виды тестирования как:
- юнит тестирование,
- тестирование верстки,
- e2e-тестирование,
- тестирование производительности для FE
Также мы коснемся таких фундаментальных вещей, как:
- Что такое F.I.R.S.T
- Где заканчивается ответственность разработчика и начинает - ответственность QA инженера
- Как договариваться с бэкенд разработчиками
- И конечно, почему тесты нужны.
Testing Experience - Evolution of Test Automation FrameworksŁukasz Morawski
Implementing automated tests is something that everybody wants to do. If you ask
any tester, test automation is their aim. And while it may be the golden target, very
few testers take pains to assess the required knowledge, under the illusion that a
programming language or expensive tool will suffice to cope with all problems likely
to arise. This is not true. Writing good automated tests is much harder than that,
requiring knowledge this article will make clear
This document discusses automated acceptance testing for ASP.NET applications. It begins with a demonstration of using Selenium WebDriver to automate a Google search. The document then covers topics like the testing pipeline, challenges with real-world testing, focusing tests on solving specific pain points, and designing UI for testability. It emphasizes that UI tests should validate scenarios rather than individual actions and should focus on the most critical tests. The document also discusses tools, techniques, and strategies for testing databases, legacy systems, and more.
Test-driven development (TDD) involves writing unit tests before writing code to help ensure code quality and avoid omitted tests. The document discusses the NUnit testing framework for .NET, which uses attributes to identify test fixtures, methods, and setup/teardown functionality. It also covers how to write tests using assertions and run tests using the NUnit GUI or console applications.
Unit tests give developers and testers a quick way to look for logic errors in the methods of classes in Visual C#, Visual Basic, and Visual C++ projects. A unit test can be created one time and run every time that source code is changed to make sure that no bugs are introduced.
TDD is a design technique where tests are written before code to determine requirements. The Red-Green-Refactor process is followed: 1) Write a test that fails (red), 2) Write minimum code to pass the test (green), 3) Refactor code. TDD ensures quality, keeps code simple and testable, and allows for rapid change. Writing tests first helps design by clarifying requirements and preventing bugs.
Unit tests exercise individual classes in isolation by replacing collaborators with mock objects. Mocks simplify testing by checking behavior rather than state. Popular mocking libraries like EasyMock and Mockito dynamically generate mocks at test runtime to verify expectations and behavior without manually writing stubs. While classical TDD uses real objects, mockist TDD always uses mocks for collaborators, which can promote looser coupling and interfaces in code design.
- Unit testing involves writing code to test individual units or components of an application to ensure they perform as expected.
- The document discusses setting up a unit testing framework for WordPress plugins and themes using PHPUnit and WP-CLI. It provides steps to generate initial test files and install dependencies to support unit testing.
- Examples of writing unit tests are given, including how to structure tests with assertions to validate the behavior of functions and methods. Maintaining well-organized test files and cases is important for an effective testing suite.
This document discusses the importance of unit testing JavaScript code. It provides reasons for testing JavaScript, such as avoiding bugs when refactoring code or introducing errors. The document discusses how to write testable JavaScript by separating business logic from views. It also recommends choosing JavaScript unit testing tools like Jasmine and Siesta, and integrating tests into continuous integration processes to run automatically on commits. Functional testing tools like Selenium are also mentioned for testing user interactions across browsers.
Similar to JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial (20)
Sudheer Mechineni, Head of Application Frameworks, Standard Chartered Bank
Discover how Standard Chartered Bank harnessed the power of Neo4j to transform complex data access challenges into a dynamic, scalable graph database solution. This keynote will cover their journey from initial adoption to deploying a fully automated, enterprise-grade causal cluster, highlighting key strategies for modelling organisational changes and ensuring robust disaster recovery. Learn how these innovations have not only enhanced Standard Chartered Bank’s data infrastructure but also positioned them as pioneers in the banking sector’s adoption of graph technology.
Full-RAG: A modern architecture for hyper-personalizationZilliz
Mike Del Balso, CEO & Co-Founder at Tecton, presents "Full RAG," a novel approach to AI recommendation systems, aiming to push beyond the limitations of traditional models through a deep integration of contextual insights and real-time data, leveraging the Retrieval-Augmented Generation architecture. This talk will outline Full RAG's potential to significantly enhance personalization, address engineering challenges such as data management and model training, and introduce data enrichment with reranking as a key solution. Attendees will gain crucial insights into the importance of hyperpersonalization in AI, the capabilities of Full RAG for advanced personalization, and strategies for managing complex data integrations for deploying cutting-edge AI solutions.
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...Neo4j
Leonard Jayamohan, Partner & Generative AI Lead, Deloitte
This keynote will reveal how Deloitte leverages Neo4j’s graph power for groundbreaking digital twin solutions, achieving a staggering 100x performance boost. Discover the essential role knowledge graphs play in successful generative AI implementations. Plus, get an exclusive look at an innovative Neo4j + Generative AI solution Deloitte is developing in-house.
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc
How does your privacy program stack up against your peers? What challenges are privacy teams tackling and prioritizing in 2024?
In the fifth annual Global Privacy Benchmarks Survey, we asked over 1,800 global privacy professionals and business executives to share their perspectives on the current state of privacy inside and outside of their organizations. This year’s report focused on emerging areas of importance for privacy and compliance professionals, including considerations and implications of Artificial Intelligence (AI) technologies, building brand trust, and different approaches for achieving higher privacy competence scores.
See how organizational priorities and strategic approaches to data security and privacy are evolving around the globe.
This webinar will review:
- The top 10 privacy insights from the fifth annual Global Privacy Benchmarks Survey
- The top challenges for privacy leaders, practitioners, and organizations in 2024
- Key themes to consider in developing and maintaining your privacy program
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
Communications Mining Series - Zero to Hero - Session 1DianaGray10
This session provides introduction to UiPath Communication Mining, importance and platform overview. You will acquire a good understand of the phases in Communication Mining as we go over the platform with you. Topics covered:
• Communication Mining Overview
• Why is it important?
• How can it help today’s business and the benefits
• Phases in Communication Mining
• Demo on Platform overview
• Q/A
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!SOFTTECHHUB
As the digital landscape continually evolves, operating systems play a critical role in shaping user experiences and productivity. The launch of Nitrux Linux 3.5.0 marks a significant milestone, offering a robust alternative to traditional systems such as Windows 11. This article delves into the essence of Nitrux Linux 3.5.0, exploring its unique features, advantages, and how it stands as a compelling choice for both casual users and tech enthusiasts.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Threats to mobile devices are more prevalent and increasing in scope and complexity. Users of mobile devices desire to take full advantage of the features
available on those devices, but many of the features provide convenience and capability but sacrifice security. This best practices guide outlines steps the users can take to better protect personal devices and information.
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfMalak Abu Hammad
Discover how MongoDB Atlas and vector search technology can revolutionize your application's search capabilities. This comprehensive presentation covers:
* What is Vector Search?
* Importance and benefits of vector search
* Practical use cases across various industries
* Step-by-step implementation guide
* Live demos with code snippets
* Enhancing LLM capabilities with vector search
* Best practices and optimization strategies
Perfect for developers, AI enthusiasts, and tech leaders. Learn how to leverage MongoDB Atlas to deliver highly relevant, context-aware search results, transforming your data retrieval process. Stay ahead in tech innovation and maximize the potential of your applications.
#MongoDB #VectorSearch #AI #SemanticSearch #TechInnovation #DataScience #LLM #MachineLearning #SearchTechnology
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIVladimir Iglovikov, Ph.D.
Presented by Vladimir Iglovikov:
- https://www.linkedin.com/in/iglovikov/
- https://x.com/viglovikov
- https://www.instagram.com/ternaus/
This presentation delves into the journey of Albumentations.ai, a highly successful open-source library for data augmentation.
Created out of a necessity for superior performance in Kaggle competitions, Albumentations has grown to become a widely used tool among data scientists and machine learning practitioners.
This case study covers various aspects, including:
People: The contributors and community that have supported Albumentations.
Metrics: The success indicators such as downloads, daily active users, GitHub stars, and financial contributions.
Challenges: The hurdles in monetizing open-source projects and measuring user engagement.
Development Practices: Best practices for creating, maintaining, and scaling open-source libraries, including code hygiene, CI/CD, and fast iteration.
Community Building: Strategies for making adoption easy, iterating quickly, and fostering a vibrant, engaged community.
Marketing: Both online and offline marketing tactics, focusing on real, impactful interactions and collaborations.
Mental Health: Maintaining balance and not feeling pressured by user demands.
Key insights include the importance of automation, making the adoption process seamless, and leveraging offline interactions for marketing. The presentation also emphasizes the need for continuous small improvements and building a friendly, inclusive community that contributes to the project's growth.
Vladimir Iglovikov brings his extensive experience as a Kaggle Grandmaster, ex-Staff ML Engineer at Lyft, sharing valuable lessons and practical advice for anyone looking to enhance the adoption of their open-source projects.
Explore more about Albumentations and join the community at:
GitHub: https://github.com/albumentations-team/albumentations
Website: https://albumentations.ai/
LinkedIn: https://www.linkedin.com/company/100504475
Twitter: https://x.com/albumentations
Dr. Sean Tan, Head of Data Science, Changi Airport Group
Discover how Changi Airport Group (CAG) leverages graph technologies and generative AI to revolutionize their search capabilities. This session delves into the unique search needs of CAG’s diverse passengers and customers, showcasing how graph data structures enhance the accuracy and relevance of AI-generated search results, mitigating the risk of “hallucinations” and improving the overall customer journey.
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfPaige Cruz
Monitoring and observability aren’t traditionally found in software curriculums and many of us cobble this knowledge together from whatever vendor or ecosystem we were first introduced to and whatever is a part of your current company’s observability stack.
While the dev and ops silo continues to crumble….many organizations still relegate monitoring & observability as the purview of ops, infra and SRE teams. This is a mistake - achieving a highly observable system requires collaboration up and down the stack.
I, a former op, would like to extend an invitation to all application developers to join the observability party will share these foundational concepts to build on:
For the full video of this presentation, please visit: https://www.edge-ai-vision.com/2024/06/building-and-scaling-ai-applications-with-the-nx-ai-manager-a-presentation-from-network-optix/
Robin van Emden, Senior Director of Data Science at Network Optix, presents the “Building and Scaling AI Applications with the Nx AI Manager,” tutorial at the May 2024 Embedded Vision Summit.
In this presentation, van Emden covers the basics of scaling edge AI solutions using the Nx tool kit. He emphasizes the process of developing AI models and deploying them globally. He also showcases the conversion of AI models and the creation of effective edge AI pipelines, with a focus on pre-processing, model conversion, selecting the appropriate inference engine for the target hardware and post-processing.
van Emden shows how Nx can simplify the developer’s life and facilitate a rapid transition from concept to production-ready applications.He provides valuable insights into developing scalable and efficient edge AI solutions, with a strong focus on practical implementation.
2. Points to Discuss
Unit Testing & Test Driven Development
Debugging JS
Writing Testable Code
Designing own testing framework
QUnit
QUnit API
Mocking AJAX
Testing Forms
Code coverage using Blankets
Automated Testing (a brief introduction)
2
3. How do you test your JS?
1. Write your JavaScript code
2. See if it works in your favourite browser
3. Change something + [F5]
4. If it doesn't work repeat #3 until you make it work or you
go crazy...
5. In case you made it work, discover few days/weeks later
that it doesn't work in another browser
3
5. Unit Testing
In computer programming, unit testing is a procedure
used to validate that individual modules or units of source
code are working properly.
Unit testing is used for
(i) Test Driven Development
(ii) Fixing bugs
(iii) Regression testing
5
6. Test Driven Development
Test-Driven Development (TDD) is a computer
programming technique that involves repeatedly first
writing a test case and then implementing only the code
necessary to pass the test.
Test-driven development is a method of designing
software, not merely a method of testing.
6
7. Test Driven Development
TDD in its simplest form is just this:
Write your tests
Watch them fail
Make them pass
Refactor
Repeat
7
10. What do you need?
A UnitTesting framework
Development Environment
10
11. Tools
Firebug -The popular developer extension for Firefox that got the ball rolling.
See http://getfirebug.org/.
IE DeveloperTools - Included in Internet Explorer 8 and later.
Opera Dragonfly - Included in Opera 9.5 and newer.Also works with mobile versions of Opera.
WebKit DeveloperTools - Introduced in Safari 3, dramatically improved as of Safari 4, and now available in
Chrome.
Logging - http://patik.com/blog/complete-cross-browser-console-log/
1. alert()
2. Console.log()
3. Common logging method that for all modern browsers
function log() {
try {
console.log.apply(console, arguments);
} catch (e) {
try {
opera.postError.apply(opera, arguments);
} catch (e) {
alert(Array.prototype.join.call(arguments," "));
}
}
}
1.Tries to log message using the
most common method
2. Catches any failure in logging
3.Tries to log the Opera way
Uses alert if all else fails
Testing and debugging - Debugging code
12. Breakpoints allow us to halt execution at a specific line of code so we can take a gander at the state.
<!DOCTYPE html>
<html>
<head>
<title>Listing 2.2</title>
<script type="text/javascript" src="log.js"></script>
<script type="text/javascript">
var x = 213;
log(x);
</script>
</head>
<body>
</body>
</html>
Testing and debugging - Breakpoints
13. Good tests make Good code - Emphasis on the word good.
It's quite possible to have an extensive test suite that doesn't really help the quality of our
code, if the tests are poorly constructed.
Good tests exhibit three important characteristics:
1. Repeatability - Our test results should be highly reproducible.Tests run repeatedly should always produce
the exact same results. If test results are nondeterministic, how would we know which results are valid and which
are invalid?
2. Simplicity - Our tests should focus on testing one thing.We should strive to remove as much HTML markup,
CSS, or JavaScript as we can without disrupting the intent of the test case.The more we remove, the greater the
likelihood that the test case will only be influenced by the specific code that we’re testing.
3. Independence - Our tests should execute in isolation.We must avoid making the results from one test
dependent upon another. Breaking tests down into the smallest possible
Test generation
14. A test suite should serve as a fundamental part of your development workflow, so you
should pick a suite that works particularly well for your coding style and your
code
base.
JavaScript unit testing framework features
• The ability to simulate browser behaviour (clicks, keypresses, and so on)
• Interactive control of tests (pausing and resuming tests)
• Handling asynchronous test timeouts
• The ability to filter which tests are to be executed
Testing Frameworks
16. The fundamentals of a test suite
The fundamentals of a test suite
1. Aggregate all the individual tests into a single unit
2. Run the in Bulk
3. Providing a single resource that can be run easily and repeatedly
How to construct a test suite
Q. Why would I want to build a new test suite,WhenThere are already a number of good-quality suites
to choose from?
A. Building your own test suite can serve as a good learning experience, especially when looking at how
asynchronous testing works.
16
17. The Assertion – (assert.html)
17
1. The core of a unit-testing framework is its assertion method, usually named
assert().
2. This takes a value—an expression whose premise is asserted—and a
description that describes the purpose of the assertion. If the value
evaluates to true
3. Either the assertion passes or it’s considered a failure.
4. The associated message is usually logged with an appropriate pass/fail
indicator.
20. Test Groups – (test_group.html)
1. Grouping assertions together in a testing context to form test
groups.
2.Test group will likely represent a collection of assertions as they
relate to a single method in our API or application
3. If any assertion fails, then the entire test group is marked as failing
20
21. So what's the first step to sanity?
WRITE TESTABLE CODE
21
22. What's wrong with this code?
js_sample_001.js
(inline functions and more inside, ajax
directly hooked to element, etc.)
22
32. Now what about testing?
Popular JS Unit-testing frameworks:
QUnit
Jasmine
UnitJS
JsUnit (no longer actively maintained)
Some other – see:
http://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#JavaScript
32
33. What's about QUnit?
QUnit is a powerful, easy-to-use JavaScript unit
testing framework.
Supports the same browsers as jQuery 1.x.That's
IE6+ and Current - 1 for Chrome, Firefox, Safari
and Opera.
Used by the jQuery project to test jQuery,
jQuery UI, jQuery Mobile
Can be used to test any generic JavaScript code,
including itself
Very easy to install – just include JS & CSS file in
your HTML
33
37. Test : QUnit.test( name, test )
Adds a test to run.
Testing the most common, synchronous code
Qunit.test(“name of the test”, function() {
//write down the assertions
});
function: Function to close over assertions
37
38. Test : expect()
Specify how many assertions are expected to run
within a test.
If the number of assertions run does not match the
expected count, the test will fail.
test(”expected assertions", function() {
expect( 2 );
//two assertions are expected
});
38
42. Assert - notEqual()
notEqual( actual, expected, message )
A comparison assertion that passes if actual !=
expected.
test("notEqual”, function() {
expect(3);
var actual = 5 - 4;
notEqual(actual, 0, "passes because 1 != 0");
notEqual(actual, false, "passes because 1 != false");
notEqual(actual, true, "fails because 1 == true");
});
42
43. Assert - strictEqual()
strictEqual( actual, expected, message )
A comparison assertion that passes if actual ===
expected.
test("notEqual”, function() {
expect(3);
var actual = 5 - 4;
strictEqual(actual, 1, "passes because 1 === 1");
strictEqual(actual, true, "fails because 1 !== true");
strictEqual(actual, false, "fails because 1 !== false");
});
43
44. Assert - notStrictEqual()
notStrictEqual( actual, expected, message )
A comparison assertion that passes if actual !==
expected.
test("notStrictEqual”, function() {
expect(3);
var actual = 5 - 4;
notStrictEqual(actual, 1, "fails because 1 === 1");
notStrictEqual(actual, true, "passes because 1 !== true");
notStrictEqual(actual, false, "passes because 1 !== false");
});
44
45. Assert - deepEqual ()
deepEqual( actual, expected, message )
Recursive comparison assertion, working on primitives,
arrays and objects, using ===.
test("deepEqual”, function() {
expect(3);
var actual = {a: 1};
equal( actual, {a: 1}, "fails because objects are different");
deepEqual(actual, {a: 1}, "passes because objects are equivalent");
deepEqual(actual, {a: "1"}, "fails because '1' !== 1");
});
45
46. Assert - notDeepEqual()
notDeepEqual( actual, expected, message )
Recursive comparison assertion.The result of
deepEqual, inverted.
test("notDeepEqual”, function() {
expect(3);
var actual = {a: 1};
notEqual( actual, {a: 1}, "passes because objects are different"); notDeepEqual(actual, {a:
1}, "fails because objects are equivalent"); notDeepEqual(actual, {a: "1"}, "passes because '1' !==
1");
});
46
47. Assert - throws()
Assertion to test if a callback throws an exception
when run and optionally compare the thrown error.
test("throws”, function() {
expect(3);
throws(
function() { throw new Error("Look me, I'm an error!"); },
"passes because an error is thrown inside the callback”
);
throws(
function() { x // ReferenceError: x is not defined },
"passes because an error is thrown inside the callback”
);
throws (
function() { var a = 1; },
"fails because no error is thrown inside the callback”
);
});
47
48. Tests Should be Atomic
Execution order cannot be guaranteed!
Each test should be independent from one another.
QUnit.test() is used to keep test cases atomic.
48
49. Async Control : QUnit.asyncTest
For testing asynchronous code, QUnit.asyncTest will
automatically stop the test runner and wait for your
code to call QUnit.start() to continue.
The following illustrates an asynchronous test that
waits 1 second before resuming
QUnit.asyncTest( "asynchronous test: one second later!", function(
assert ) {
expect( 1 );
setTimeout(function() {
assert.ok( true, "Passed and ready to resume!" );
QUnit.start(); }, 1000);
});
49
50. Async Control : QUnit.stop()
Increase the number of QUnit.start() calls the
testrunner should wait for before continuing.
When your async test has multiple exit points, call
QUnit.stop() multiple times or use the increment
argument.
QUnit.test( "a test", function( assert ){
QUnit.stop();
setTimeout(function(){
assert.equals("somedata" , "someExpectedValue" );
QUnit.start(); }, 150 );
});
50
51. Grouping Tests : QUnit.module()
It groups tests together to keep them logically
organized and be able to run a specific group of tests
on their own.
All tests that occur after a call to QUnit.module() will
be grouped into that module.The test names will all be
preceded by the module name in the test results.
QUnit.module( "group a" );//tests for module a
QUnit.module( "group b" );//test for module b
51
52. Grouping Tests : QUnit.module()
QUnit.module() can also be used to extract common
code from tests within that module.
The QUnit.module() function takes an optional second
parameter to define functions to run before and after
each test within the module
QUnit.module( "module", {
setup: function( assert )
{//any setup task},
teardown: function( assert )
{//task to be performed after test completion}
});
QUnit.test( "test with setup and teardown", function()
{
//test cases
});
52
53. Callbacks
When integrating QUnit into other tools like CI
servers, use these callbacks as an API to read test
results.
QUnit.begin()
QUnit.done()
QUnit.moduleStart()
QUnit.moduleDone()
QUnit.testStart()
QUnit.testDone()
53
54. Mocking Ajax with the JQuery Mockjax
Library
MockAjax
Downlaod it from https://github.com/mobz/mock-ajax
MockAjax is an mock XMLHttpRequest implementation
designed to allow asynchronous XHR requests to be run
inside a synchronous testing framework.
54
55. Mockjax benifits
Mock out Ajax requests, so a server is not required to test
server dependent code
Allow asynchronous requests to run synchronously, allowing
tests to run much faster than normal
Allow you to test multiple simultaneous inflight requests
Allow tricky edge cases to be tested with ease
server timeouts
receiving server responses out of order
404’s
server errors
Allows tests that use setTimeout to run instantly and reliably
also supports asynchronous and synchronous ajax without
blocking
55
58. Testing User Action
Problem
Code that relies on actions initiated by the user can't be
tested by just calling a function. Usually an anonymous
function is bound to an element's event, e.g., a click,
which has to be simulated.
Solution
Trigger() event using jQuery trigger
triggerHandler of jQuery can be used if you don’t wanr
the native browser event to be triggered
If That is not enough
https://github.com/bitovi/syn
http://tinymce.ephox.com/jsrobot
http://dojotoolkit.org/reference-
guide/1.8/util/dohrobot.html
https://github.com/gtramontina/keyvent.js
58
61. Testing Scope - Variable
function outer() {
var a = 1;
function inner() {}
var b = 2;
if (a == 1) {
var c = 3;
}
QUnit.test( "Testing Variable Scope in function", function( assert ){
assert.ok(typeof c === 'number', "c is in scope");
});
}
QUnit.test( "Testing Variable Scope", function( assert ){
assert.ok(true, "some descriptive text");
assert.ok(typeof inner !== 'function', "inner() is not in scope");
assert.ok(typeof outer === 'function', "outer() is in scope");
assert.ok(typeof b !== 'number', "b is not in scope");
assert.ok(typeof a !== 'number', "a is not in scope");
outer();
});
61
62. Testing Scope – Function p1
function isFunction() { return true; }
var doSomething = function () { return true; };
window.testFunction = function () {return true; };
function outer() {
QUnit.test("Testing Function Scope before declaration", function( assert ){
assert.ok(typeof inner === "function", "inner() in scope before declaration");
});
function inner() {}
QUnit.test("Testing Function Scope after declaration", function( assert ){
assert.ok(typeof inner === "function", "inner() in scope after declaration");
assert.ok(window.inner === undefined, "inner() in global scope");
});
}
62
63. Testing Scope – Function p2
QUnit.test("Testing Function Scope", function( assert ){
assert.ok(typeof window.isFunction === "function", "isFunction() defined");
assert.ok(isFunction.name === "isFunction", "isFunction() has a name");
assert.ok(typeof window.doSomething === "function", "doSomething() defined");
assert.ok(doSomething.name === "", "doSomething() has no name");
assert.ok(typeof window.testFunction === "function", "testFunction() defined");
outer();
assert.ok(window.inner === undefined, "inner() still not in global scope");
window.doCoding = function writeCode() {
return true;
};
assert.ok(window.doCoding.name === 'writeCode', "wieldSword's real name is
writeCode");
});
63