2016-06-22 36 views
3

我有这样的功能:茉莉:如何指望承诺处理程序没有抛出异常

reload() { 
    myService.queryData() 
     .done(...) 
     .always(() => throw "fake exception"); //just to simulate the failure 
} 

我想我的测试重装功能,并确保它不会抛出异常,也不承诺回调做。

describe("reload", function() { 
    it("does not throw exception", function (done) { 

     spyOn(myService, "queryData").and.callFake(() => { 
      let deffered = $.deffered(); 
      setTimeOut(() => deffered.reject(), 0) 
      return deffered.promise(); 
     }); 

     reload(); 
     setTimeout(() => { 
      //this is evaluated after the exception has been thrown, but 
      //how to check whether exception has been thrown 
     }, 2); 
    }); 
}); 

编辑:我可能无法在某些情况下,该函数的返回类型已经被定义返回一个承诺,如组件的生命周期事件:

MyComponent extends React.Component { 
    componentDidMount() { 
     this.load(
      galleryService.nodes().then(galleryResult => this.setState({ nodes: galleryResult.nodes })) 
     ); 
     this.load(
      galleryService.caches().then(cachesResult => this.setState({ caches: cachesResult.caches })) 
     ); 
    } 
} 

var myComponent = React.createElement(MyComponent); 
TestUtils.renderIntoDocument(myComponent); //this triggers the componentDidMount event and I need to make sure it won't throw error. 
+0

不能使用'Promise.all'或'Promise.race'协调在您的编辑片段流? – MarcoL

+0

我可以,但componentDidMount由框架(REACT)定义为返回void的函数,我不直接调用它。当我执行'TestUtils.renderIntoDocument(...)'时,它被框架调用。我希望我可以孤立问题香草javascript,但我没有正确阐明问题... – Liero

+0

我仍然不明白为什么你不能返回一个'Promise.all'包含'componentDidMount所有的承诺'或者将相关的代码分解成一个单独的,可测试的函数,你可以从'componentDidMount'调用。 –

回答

0

我相信,刺探window.onerror是要走的路:

describe("reload", function() { 
    it("does not throw an exception", function (done) { 

      spyOn(window, 'onerror').and.callFake((error: any, e: any) => { 
       fail(error); 
      }); 

      spyOn(myService, "queryData").and.callFake(() => { 
       let deffered = $.deffered(); 
       setTimeout(deffered.reject, 0); 
       return deffered.promise(); 
      }); 
     }); 
     setTimeout(done, 2); 
    }); 
}); 
3

reload返回的承诺它创建。在您的测试情况下,附加catch处理函数,这将触发测试失败:问题后

reload().catch(err => done.fail(err)); 

更新被编辑:如果你不能改变你原来的函数的返回值,那么相关的部分分解出成单独的功能。例如:

function reloadNodes() { 
    return somePromise(); 
} 

function reloadCaches() { 
    return anotherPromise(); 
} 

function reload() { 
    reloadNodes(); 
    reloadCaches(); 
} 

然后,您可以测试reloadNodesreloadCaches而不是reload。显然,您不需要为每个承诺创建一个单独的函数,而是在适当的地方使用类似Promise.all的承诺来组合您的承诺。

+0

这是我做到的方式,但总是不可能回到承诺,看看我的编辑。 – Liero

+0

@Liero查看我的更新 –

+0

以后我会接受这个答案,因为它回答了我的原始问题,但实际上并没有解决我的问题。我承认我描述得很差 – Liero

相关问题