Bjo*_*orn 1 javascript testing mocking flowtype
我正在使用flowtype来注释我的JavaScript中的类型.在我的测试中,我也想利用flowtype.
我正在测试一个函数被赋予一个参数,该参数是一个具有另一个函数的对象,并且该另一个函数被调用了具有期望参数的正确次数.
示例代码:
function foo(obj: Bar) {
obj.bar('bar');
}
Run Code Online (Sandbox Code Playgroud)
示例测试:
test('foo gets bar', t => {
const mockBar: Bar = {
bar: sinon.stub(),
};
foo(mockBar);
t.true(mockBar.bar.calledWith('bar'));
});
Run Code Online (Sandbox Code Playgroud)
现在Bar是一个非常复杂的类型,具有很多属性等等,并且不容易完全模拟,在这里我只想测试'bar'给出的.Flowtype没有这个和错误说我mockBar不是真的Bar,我不知道该做什么,除了不在测试中使用flowtype或Bar完全以某种方式模拟出来这将是一个很大的工作一点点测试.
我可以简单地以某种方式强制将模拟转换为Bar,以便flowtype会满意吗?
实际上,我可能找到了更好的解决方案.
// Upcast mockBar to any then downcast any to Bar.
// Unsafe downcasting from any is allowed: OK
((mockBar: any): Bar);
Run Code Online (Sandbox Code Playgroud)
上面的表达式将具有类型Bar.
资料来源:https://flowtype.org/blog/2015/02/18/Typecasts.html
这种方法的好处是只忽略类型转换错误.仍然会检测到例如不存在的变量的错误.
| 归档时间: |
|
| 查看次数: |
323 次 |
| 最近记录: |