我有很多中间件。这是其中之一。如何在类型脚本上进行类型一致性和context.state验证来测试我的中间件?
async function internationalizationPlugin(
context: ParameterizedContext<AppState, AppContext>,
next: Next
) {
context.state.i18n = await (i18next as any).createInstance({
lng: context.state.language,
fallbackLng: 'en',
})
await next()
}
答案 0 :(得分:0)
短绒棉衣将检查类型合规性,并将能够对其进行更多自定义。但是,您只需要确保将函数导出到测试文件中,然后运行不是100%复制/可粘贴代码的expect(typeof context).to.be(ParameterizedContext<AppState, AppContext>)
,但我认为它是正确的。另外,对于可测试性,如果您从中间件中创建一个类来简化导入和测试,则可能会更容易。
答案 1 :(得分:0)
这是我的简单类型支持解决方案。我不确定它是否适合所有人。
import * as httpMocks from 'node-mocks-http'
import * as Koa from 'koa'
export interface MockContext<RequestBody = undefined> extends Koa.Context {
request: Koa.Context['request'] & {
body?: RequestBody
}
}
export const koaMockContext = <
State = Koa.DefaultState,
Context = MockContext,
RequestBody = undefined
>(
requestBody?: RequestBody
) => {
const req = httpMocks.createRequest()
const res = httpMocks.createResponse()
const app = new Koa<State, Context>()
const context = app.createContext(req, res) as MockContext<RequestBody> & Koa.ParameterizedContext<State, Context>
res.statusCode = 404
context.request.body = requestBody
return context
}
还有例子
import { AppContext, AppState } from './types'
import { koaMockContext } from './utils'
import { internationalizationPlugin } from '../src/internationalizationPlugin'
describe('internationalizationPlugin', () => {
const ctx = koaMockContext<AppState, AppContext>()
it('should not be undefined', async () => {
await internationalizationPlugin(ctx, async () => {})
expect(ctx.state.i18n).not.toBe(undefined)
})
})