I'm using jasmine on an angular2 project and having some trouble writing a custom matcher for a test. I want to be able to compare two relatively complex objects. I found this article which claims to solve the issue but it simply results in a typescript error stating that it doesn't recognize the new method on jasmine's Matchers object. The relevant code is this:
declare module jasmine {
interface Matchers {
toBeNumeric(): void;
}
}
Another article gives a similar, but slightly different solution that gives the same error.
declare namespace jasmine {
interface Matchers {
toHaveText(expected: string): boolean;
}
}
I tried this
let m: jasmine.Matchers = expect(someSpy.someMethod).toHaveBeenCalled();
and got this error:
Type 'jasmine.Matchers' is not assignable to type 'jasmine.Matchers'. Two different types with this name exist, but they are unrelated.
That seems to indicate that the declare namespace jasmine statement is creating a new jasmine namespace rather than extending the existing one.
So how can I create my own matcher that typescript will be happy with?
Basically, your second example ("declare namespace") is the way to go, with your logic for the matchers somewhere else, of course.
You're welcome to take a look at https://github.com/fluffynuts/polymer-ts-scratch/tree/5eb799f7c8d144dd8239ab2d2bcc72821327cb24/src/specs/test-utils/jasmine-matchers where I have written some Jasmine matchers and typings to go along with them -- though technically I wrote the actual matchers in Javascript and just named the logic files .ts to placate my build process.
You will need to install
@types/jasmine-- and keep it current.Just bear in mind that different versions of
@types/jasminemay break things; specifically, the commit linked above was when Jasmine types introduced theMatcherstype having a type parameter (ie,Matchers<T>) which broke all my .d.ts files.