Mocking in JavaScript
Mocking is a fundamental concept in software testing, particularly within JavaScript application development. It involves creating simulated versions of objects or functions to mimic their behavior in a controlled environment. This technique is essential for isolating the system under test, ensuring that tests are not influenced by external dependencies, and allowing developers to focus on the specific functionality being tested.
Mocking in JavaScript Application Design
Mocking is a crucial practice in JavaScript application design, providing the tools and techniques necessary to create a controlled and reliable testing environment. It allows developers to simulate and verify interactions with external dependencies, ensuring that their code is robust and well-tested.
Sinon.js: A Tool for Mocking
Sinon.js is a powerful library that facilitates the creation of mocks, spies, and stubs in JavaScript. It provides developers with the tools to simulate and control the behavior of functions and objects, making it significantly easier to test code that interacts with external dependencies. By using Sinon.js, developers can create a controlled testing environment where they can dictate how dependencies behave, ensuring that tests are reliable and repeatable.
Spies in Mocking
Spies are a specific type of function used in mocking that record information about their usage. They track details such as the number of times they were called and the arguments they were called with. Spies are invaluable in testing because they allow developers to verify that functions are being called as expected without altering the functions' behavior. This verification is crucial for ensuring that the code interacts with its dependencies correctly.
Proxies in Mocking
Proxies are another advanced concept in mocking, used to intercept and control interactions with objects or functions. They provide developers with the ability to modify behavior, track interactions, and simulate different scenarios. This level of control is particularly useful for testing complex systems where interactions with dependencies need to be carefully managed and observed. Proxies enable developers to create a more flexible and controlled testing environment, allowing for more comprehensive testing of various scenarios and edge cases.
Mocking in Functional Programming
In the context of functional programming, mocking is a testing technique that involves using mock objects to simulate the behavior of a function's external dependencies. This approach is particularly useful in creating predictable and consistent tests by controlling the expected behavior of these dependencies.
Mocking External Dependencies
When a function relies on external dependencies, such as databases or APIs, it can be challenging to test its behavior in isolation. Mocking these dependencies allows developers to simulate their behavior, providing a controlled environment for testing. This is achieved by creating mock objects that mimic the interfaces of the actual dependencies, enabling the function to interact with them as if they were real.
By controlling the behavior of these mock objects, developers can specify what the function should expect in terms of return values, the number of times a method is called, and the arguments it receives. This level of control is crucial for testing functions that have side effects or rely on external resources, as it allows for consistent and repeatable tests.
Example: Mocking with QUnit and Sinon.JS
The following example demonstrates how to use mocking to test a function that interacts with a student database. The function findStudent is designed to fetch student records, and its behavior is tested using QUnit and Sinon.JS.
Listing 6.3. Mocking the external dependency of findStudent
var studentStore, mockContext;
QUnit.module('CH06',
{
beforeEach: function() { #1
studentDb = DB('students');
mockContext = sinon.mock(studentDb);
},
afterEach: function() { #2
mockContext.verify(); #3
mockContext.restore();
}
});
QUnit.test(showStudent: findStudent returning null',
function (assert) {
mockContext.expects('get').once().returns(null); #4
const findStudent = safefetchRecord(studentStore);
assert.ok(findStudent('xxx-xx-xxxx').isLeft); #5
});
QUnit.test('showStudent: findStudent returning valid object',
function (assert) {
mockContext.expects('get').once().returns( #6
new Student('Alonzo', 'Church', 'Princeton').
setSsn('444-44-4444'));
const findStudent = safefetchRecord(studentStore);
assert.ok(findStudent('444-44-4444').isRight); #7
});
#1 - Prepares the mock context for all unit tests
#2 - Cleans up after each test
#3 - Verifies the assertions set forth in the mock configuration
#4 - On the first unit test, the mock object simulates a call to its query method (strictly once) that returns null.
#5 - Asserting the returned value is wrapped in an Either.Left
#6 - On the second unit test, the mock object simulates a call to query with a valid result.
#7 - Asserting the valid response is wrapped inside an Either.Right
In this example, the findStudent function is tested in two scenarios: one where it returns null and another where it returns a valid student object. The mock context is set up to simulate these scenarios, allowing the tests to verify that the function behaves as expected in each case.
Figure 6.7 The result of running the tests with QUnit and Sinon.JS for the testable parts of
showStudent.
By using mocking, developers can ensure that their tests are both comprehensive and isolated from external factors, leading to more robust and maintainable code.
| Book Title | Usage of Mocking | Technical Depth | Connections to Other Concepts | Examples Used | Practical Application |
|------------|------------------|-----------------|-------------------------------|---------------|-----------------------|
| [JavaScript Application Design: A Build First Approach](https://www.manning.com/books/javascript-application-design) | Discusses mocking as a crucial concept in software testing, focusing on creating fake versions of objects or functions to simulate behavior. [more](https://livebook.manning.com/book/javascript-application-design/chapter-8/86) | Explores advanced concepts like Sinon.js, spies, and proxies for controlling and simulating function behavior. [more](https://livebook.manning.com/book/javascript-application-design/chapter-8/94) | Connects mocking with testing reliability and isolation from external dependencies. [more](https://livebook.manning.com/book/javascript-application-design/chapter-8/96) | Provides examples using Sinon.js to create a controlled testing environment. [more](https://livebook.manning.com/book/javascript-application-design/chapter-8/106) | Emphasizes the importance of mocking for robust and well-tested code. [more](https://livebook.manning.com/book/javascript-application-design/chapter-8/106) |
| [Functional Programming in JavaScript](https://www.manning.com/books/functional-programming-in-javascript) | Describes mocking as a technique to simulate external dependencies for predictable tests. [more](https://livebook.manning.com/book/functional-programming-in-javascript/chapter-6/82) | Details the use of mock objects to manage side effects and ensure reliable tests. [more](https://livebook.manning.com/book/functional-programming-in-javascript/chapter-6/83) | Links mocking with managing side effects and testing functions in isolation. [more](https://livebook.manning.com/book/functional-programming-in-javascript/chapter-6/83) | Demonstrates mocking with QUnit and Sinon.JS to test functions interacting with databases. [more](https://livebook.manning.com/book/functional-programming-in-javascript/chapter-6/82) | Highlights the role of mocking in creating maintainable and isolated tests. [more](https://livebook.manning.com/book/functional-programming-in-javascript/chapter-6/82) |
FAQ (Frequently asked questions)
What is mocking in testing?
How does mocking help in testing?
What does mocking external dependencies involve?
Why is mocking useful in testing functions with external resources?
What is mocking in testing?
What is Sinon.js used for?
What are spies in testing?