liveBook · Manning

Duck typing

As explained in The Art of Unit Testing 3e

Duck typing is a type-compatibility approach that accepts an object based on the operations it supports rather than its declared type or class.

Duck typing accepts an object because it supports the operations the code needs, not because it belongs to a particular declared type or class. If a real dependency and a fake dependency both provide getDay(), either can be supplied. section 3.7.2

For dependency injection and testing, duck typing means:

  • Inject an object with the same required function signature as the real dependency. section 3.7.2
  • Use a handwritten fake to control behavior, such as returning Sunday from getDay() and testing a weekend error. section 3.7.2
  • Accept that JavaScript checks compatibility at runtime; a misspelled or missing function will not be caught beforehand. section 3.7.2
  • Choose a common interface when compile-time confidence matters; that alternative requires a strongly typed language such as TypeScript. section 3.8

A fake time provider

A PasswordVerifier can receive a timeProvider object and call timeProvider.getDay(). Production code supplies a real provider; a test supplies new FakeTimeProvider(SUNDAY). The fake needs no inheritance relationship—only the function the verifier uses—so the weekend case becomes controllable and testable. section 3.7.2

Listing 3.13 Creating a handwritten stub object
function FakeTimeProvider(fakeDay) {
    this.getDay = function () {
        return fakeDay;
    }
}
 
describe('verifier', () => {
    test('class constructor: on weekends, throws exception', () => {
        const verifier = 
            new PasswordVerifier([], new FakeTimeProvider(SUNDAY));
 
        expect(() => verifier.verify('anything'))
            .toThrow("It's the weekend!");
    });
});

This listing shows a handwritten stub object and a test that injects it through a class constructor. section 3.7.2

How The Art of Unit Testing 3e covers it

How deep it goes
Explains matching function signatures, handwritten fakes, runtime checking, and a compile-time interface alternative.
Examples
Uses RealTimeProvider, FakeTimeProvider, PasswordVerifier, getDay(), and a weekend exception test.
What it assumes
Assumes basic JavaScript objects, functions, constructors, and tests while teaching dependency substitution through a small time-provider example.
What you can do after
Apply it via JavaScript object injection to substitute controllable test dependencies and exercise specific behaviors.
How it connects
Ties duck typing to dependency injection, stubs, constructor injection, unit testing, and common interfaces.

Also explained in

Compare how 3 books explain duck typing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Art of Unit Testing 3e. The section links point to the parts of the book it draws on.