在我的Angular 4组件中,我有类似的东西:
constructor(private route: ActivatedRoute) {
}
ngOnInit() {
this.myId = this.route.snapshot.params['myId'];
}
Run Code Online (Sandbox Code Playgroud)
而我正在尝试创建一个假设如下的模拟:
class MockActivatedRoute extends ActivatedRoute {
public params = Observable.of({ myId: 123 });
}
Run Code Online (Sandbox Code Playgroud)
我的测试失败了:
TypeError:无法读取undefined的属性'params'.
我怎么想嘲笑它?我是否误解了正确的用法,ActivatedRoute应该更好地使用router.subscribe我的组件?我看到一些复杂的例子,人们嘲笑快照本身,但对我来说它看起来过于复杂.
测试本身很简单:
describe('ngOnInit', () => {
it('should set up initial state properly',
() => {
const component = TestBed.createComponent(MyComponent).componentInstance;
component.ngOnInit();
expect(component.myId).toEqual('123');
});
});
Run Code Online (Sandbox Code Playgroud)
如果我只是将测试下的方法更改为以下内容 - 测试工作:
ngOnInit() {
//this.myId = this.route.snapshot.params['myId'];
this.route.params.subscribe(params => {
this.myId = params['myId'];
});
}
Run Code Online (Sandbox Code Playgroud)
显然我需要模拟Activated快照,但是有更好的方法吗?
我有以下代码和平:
IAsyncResult beginExecuteReader = command.BeginExecuteNonQuery();
while (!beginExecuteReader.IsCompleted)
{
if (controllerTask.CancellationTokenSource.IsCancellationRequested)
{
command.Cancel();
}
Thread.Sleep(100);
}
try
{
result = command.EndExecuteNonQuery(beginExecuteReader);
}
catch (SqlException exception)
{
if (exception.ErrorCode == OperationCanceled)
{
throw new OperationCanceledException();
}
throw;
}
Run Code Online (Sandbox Code Playgroud)
我如何识别,捕获的异常是由操作取消引起的.在这种情况下,ExecuteNonQuery抛出异常,错误代码为0x80131904,但这是非常普遍的异常,可能由多种原因引起.错误消息如下所示:{"当前命令发生严重错误.结果(如果有)应该被丢弃.\ r \n用户取消操作."}
除了解析错误信息之外,我没有看到任何选项...任何想法?
谢谢
PS.是的,我知道asyncronyc操作的取消命令可能不是最好的主意,因为对于.NET 2.0,MSDN上有警告,但对于.NET 4.0,这个警告被删除了.当我从另一个线程调用cancel方法时,我也不喜欢另一个实现,因为对我而言,它使代码更加困难