Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a Jasmine custom matcher Typescript definition?

I've been looking around and this question seems like a recurring thing. However, none of the solutions I've found seem to work for me.

Using the following:

{
  "typescript": "2.3.2",
  "jasmine-core": "2.6.1",
  "@types/jasmine": "2.5.47"
}

I can't get Typescript to merge the namespace declaration containing my custom matcher definition.

Adding this:

declare namespace jasmine {
  interface Matchers<T> {
    toBeAnyOf(expected: jasmine.Expected<T>, expectationFailOutput?: any): boolean;
  }
}

Hides every other type previously declared on jasmine. Compiler outputs errors such as:

[ts] Namespace 'jasmine' has no exported member 'CustomMatcherFactories'
[ts] Namespace 'jasmine' has no exported member 'CustomMatcher'.

Is there any proper way to add a custom matcher and make it play nicely with Typescript?

There's an additional issue with tslint if you are using tslint:recommended ruleset. Those rules disallow the usage of namespace or module keywords, so I had to disable the linter (or change the "no-namespace" rule) in order to try this out. Unsure how one would get around extending definitions if this is "not recommended".

like image 894
Nicolás Fantone Avatar asked May 04 '17 16:05

Nicolás Fantone


1 Answers

I had to modify three files when I added custom matchers. I created a file called matchers.ts that contained the actual matchers. I then added an import to test.ts for my matchers.ts file. Finally, I added an interface to the typings.d.ts file which contains my matcher.

matchers.ts (arbitrary name)

beforeEach(() => {
    jasmine.addMatchers({
        toContainText: () => {
            return {
                compare: (actual: HTMLElement, expectedText: string, customMessage?: string) => {
                    const actualText = actual.textContent;
                    return {
                        pass: actualText.indexOf(expectedText) > -1,
                        get message() {
                            let failureMessage = 'Expected ' + actualText + ' to contain ' + expectedText;

                            if (customMessage) {
                                failureMessage = ' ' + customMessage;
                            }

                            return failureMessage;
                        }
                    };
                }
            };
        },
    });
});

test.ts

import 'test/test-helpers/global/matchers'; (my relative filepath)

typings.d.ts

declare module jasmine {
  interface Matchers {
    toContainText(text: string, message?: string): boolean;
  }
}
like image 124
jacobisaman Avatar answered Oct 24 '22 02:10

jacobisaman