我可以将半实现的模拟转换为具有流类型的类型吗?

Can I cast a half implemented mock to a type with flowtype?

我正在使用 flowtype 来注释我 JavaScript 中的类型。在我的测试中,我也想利用 flowtype。

我正在测试一个函数是否被赋予了一个参数,该参数是一个具有另一个函数的对象,并且这个另一个函数被正确调用了预期参数的次数。

示例代码:

function foo(obj: Bar) {
   obj.bar('bar');
}

示例测试:

test('foo gets bar', t => {
    const mockBar: Bar = {
       bar: sinon.stub(),
    };
    foo(mockBar);
    t.true(mockBar.bar.calledWith('bar'));
});

现在 Bar 是一个非常复杂的类型,有很多属性等等,不容易完全模拟,在这里我只想测试 'bar' 是否已给出。 Flowtype 有 none 并且错误地说我的 mockBar 不是真正的 Bar 我不知道在这一点上除了不在测试中使用 flowtype 或以某种方式完全模拟 Bar 这对于一个小测试来说会是很多工作。

我能否以某种方式强制将 mock 强制转换为 Bar,使其成为 flowtype 会满意的方式?

您可以使用 Flow 的错误抑制注释来忽略错误。您需要在 .flowconfig.

中定义注释模式

来自docs

suppress_comment(正则表达式):定义了一个神奇的注释,用于抑制下一行中的任何 Flow 错误。例如:

suppress_comment= \(.\|\n\)*\$FlowFixMe

将匹配这样的评论:

// $FlowFixMe: suppressing this error until we can refactor
var x : string = 123;

其实,我可能找到了更好的解决方案。

// Upcast mockBar to any then downcast any to Bar.
// Unsafe downcasting from any is allowed: OK
((mockBar: any): Bar);

以上表达式的类型为 Bar

来源:https://flowtype.org/blog/2015/02/18/Typecasts.html

这种方法的好处是只忽略类型转换错误。来自例如的错误仍然会检测到不存在的变量。