【发布时间】:2018-12-30 23:36:06
【问题描述】:
有没有办法使用 Jasmine 和 Typescript 监视构造函数?
Spying on a constructor using Jasmine 所提出的解决方案无效,因为TypeScript does not expose global declarations on window。
这是我的用例:
// 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)); }
}
测试失败:
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 }) ]
});
在测试中,我并不关心构造函数的作用。我只需要验证它是否已使用正确的参数调用。这甚至听起来像是一个模拟的正确用例。
【问题讨论】:
-
你在监视它是正确的。但是测试失败了,因为它是用不同的
Book实例调用的,即使它们的“值”相同。 -
但在我使用高阶函数之前,Jasmine 测试甚至通过了不同的
Book实例。即使它是不同的实例,它似乎也会比较值。有没有办法使用单个Book实例编写测试?
标签: typescript jasmine mocking spy