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


