我使用ava(没有链接,因为我不允许使用超过2个)进行测试,并且想要输入ava的测试上下文。它是typed as any
in ava's definition file。
我特别想要的是,typescript编译器知道t.context
在以下测试中属于{foo: number}
类型:
import test from 'ava'
test.beforeEach((t) => {
t.context = { foo: 5 }
})
test('Is context typed', (t) => {
// uncaught typo
t.is(t.context.fooo, 5)
})
我尝试使用declaration merging来执行此操作,但它失败了TS2403: Subsequent variable declarations must have the same type. Variable 'context' must be of type 'any', but here has type '{ foo: number; }'.
:
declare module 'ava' {
interface ContextualTestContext {
context: {
foo: number,
}
}
}
test.beforeEach((t) => {
t.context = { foo: 5 }
})
test('Is context typed', (t) => {
// uncaught ypo
t.is(t.context.fooo, 5)
})
有没有办法这样做而不会像这样一直抛出上下文:
interface IMyContext {
foo: number
}
test.beforeEach((t) => {
t.context = { foo: 5 }
})
test('Is context typed', (t) => {
const context = <IMyContext> t.context
// caught typo
t.is(context.fooo, 5)
})
答案 0 :(得分:0)
没有通用的方法。在您的特殊情况下,您可以创建一个新的TestContext
,例如而不是
export type ContextualTest = (t: ContextualTestContext) => PromiseLike<void> | Iterator<any> | Observable | void;
使用类似
的内容export type MyContextualTest<T> = (t : TestContext & {context : T}) => PromiseLike<void> ...
并声明您自己的test
功能,该功能应与Ava兼容:
interface MyTestFunction<T> {
(name : string, run : MyContextualTest<T>)
}
import {test as avaTest} from 'ava';
const test : MyTestFunction<IMyContext> = avaTest;
这大部分未经测试,所以如果有问题,请告诉我。
答案 1 :(得分:0)
下一版本的ava可以输入上下文。然后你可以做这样的事情:
import * as ava from 'ava';
function contextualize<T>(getContext: () => T): ava.RegisterContextual<T> {
ava.test.beforeEach(t => {
Object.assign(t.context, getContext());
});
return ava.test;
}
const test = contextualize(() => {
return { foo: 'bar' };
});
test.beforeEach(t => {
t.context.foo = 123; // error: Type '123' is not assignable to type 'string'
});
test.after.always.failing.cb.serial('very long chains are properly typed', t => {
t.context.fooo = 'a value'; // error: Property 'fooo' does not exist on type '{ foo: string }'
});
test('an actual test', t => {
t.deepEqual(t.context.foo.map(c => c), ['b', 'a', 'r']); // error: Property 'map' does not exist on type 'string'
});
如果以异步方式获取上下文,则需要相应地更改contextualize
的类型签名:
function contextualize<T>(getContext: () => Promise<T>): ava.RegisterContextual<T> {
ava.test.beforeEach(async t => {
Object.assign(t.context, await getContext());
});
return ava.test;
}
const test = contextualize(() => {
const db = await mongodb.MongoClient.connect('mongodb://localhost:27017')
return { db }
});
否则,TypeScript编译器会认为t.context
是Promise,尽管它不是