Is there a way how to spy on constructor using Jasmine and Typescript?
Proposed solutions in question Spying on a constructor using Jasmine do not work because TypeScript does not expose global declarations on window
.
Here is my use case:
// higher-order function returns validation function with max length
const maxLengthValidator = maxLength => value => value.length > maxLength;
class Book {
// will be a different function instance each time the Book object is
// created causing the following test to fail
nameValidator = maxLengthValidator(42);
name = null;
constructor (name) { this.name = name; }
}
class Library {
persons = [];
storeBook (book) { this.persons.push(book); }
createBook (name) { this.storeBook(new Book(name)); }
}
Failing test:
it('createBook passes new book with provided name to storeBook', () => {
const lib = new Library();
spyOn(lib, 'storeBook');
lib.createBook('Start with Why');
expect(lib.storeBook).toHaveBeenCalledWith(new Book('Start with Why'));
// Result: Expected spy storeBook to have been called with
// [ Book({ name: 'Start with Why', nameValidator: Function }) ]
// but actual calls were
// [ Book({ name: 'Start with Why', nameValidator: Function }) ]
});
In the test, I don't really care what constructor does. I only need to verify that it has been called with the right parameter. That even sounds like a right use case for a mock.