我一直在
looking
around,这个问题看起来像
recurring thing.但是,我发现的解决方案似乎都不适合我.
使用以下内容:
{
"typescript": "2.3.2","jasmine-core": "2.6.1","@types/jasmine": "2.5.47"
}
我不能让Typescript合并包含我的自定义匹配器定义的名称空间声明.
添加这个:
declare namespace jasmine {
interface Matchers<T> {
toBeAnyOf(expected: jasmine.Expected<T>,expectationFailOutput?: any): boolean;
}
}
隐藏先前在jasmine上声明的所有其他类型.编译器输出错误,例如:
[ts] Namespace 'jasmine' has no exported member 'CustomMatcherFactories' [ts] Namespace 'jasmine' has no exported member 'CustomMatcher'.
有没有适当的方法来添加自定义匹配器并使其与Typescript很好地配合?
如果您使用的是tslint,则存在tslint的其他问题:建议的规则集.这些规则不允许使用命名空间或模块关键字,因此我必须禁用linter(或更改“no-namespace”规则)才能尝试此操作.如果“不推荐”,则不确定如何扩展定义.
解决方法
添加自定义匹配器时,我不得不修改三个文件.我创建了一个名为matchers.ts的文件,其中包含实际的匹配器.然后我为matchers.ts文件添加了test.ts的导入.最后,我在typings.d.ts文件中添加了一个包含我的匹配器的接口.
matchers.ts(任意名称)
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;
}
}