我正在使用 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 没有这些,并且错误地说我的 mockBar
不是真正的 Bar
我不知道此时除了不使用 flowtype 之外该怎么做以某种方式完全测试或模拟 Bar
,这对于一个小测试来说会是很多工作。
我能否简单地以某种方式强制将 mock 强制转换为 Bar 以一种 flowtype 会满意的方式?
最佳答案
实际上,我可能找到了更好的解决方案。
// 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
这种方法的好处是只忽略类型转换错误。来自例如的错误仍然会检测到不存在的变量。
关于javascript - 我可以将半实现的模拟转换为具有流类型的类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40274055/