我的一些单元测试涉及将无效(类型不正确的)数据传递给函数。例如:

// user.js

type User = {
    id: number,
    name: string,
    email: string
}

export function validateUser(user: User): Promise<void> {
    return new Promise((resolve, reject) => {
        // resolve if user is valid, reject if not
    })
}
// user.unit.js

import {validateUser} from '../user.js'

describe('validateUser', () => {
    it('should reject if user is not valid', () => {
        const invalidUser: User = {}
        expect(validateUser(invalidUser)).to.be.rejected
    })
})

由于invalidUser变量不符合User类型,因此出现流错误:
Cannot call validateUser with invalidUser bound to user because:
 • property id is missing in object literal [1] but exists in User [2].
 • property name is missing in object literal [1] but exists in User [2].
 • property email is missing in object literal [1] but exists in User [2].

显然,我希望此变量无效,那么如何为该单个实例禁用流类型检查?

最佳答案

根据.flowconfig [options] docs,有一个选项可以指定suppress comment。 Flow将检测到此注释,并忽略以下代码行。

默认:



因此,只需添加注释($FlowFixMe)即可取消对单行的类型检查。

// $FlowFixMe
const invalidUser: User = {}

10-04 14:36
查看更多