SinonJS-调用Stub之前的属性值

SinonJS - Property Value before Stub Called

本文关键字:属性 调用 Stub SinonJS-      更新时间:2023-09-26

我目前在中使用sinon.js进行存根。从我所看到的情况来看,使用库可以存根和监视方法,但不能监视属性。

在以下示例中,在调用submit之前,是否有方法检查state.searchText是否设置为state.suggestion

   // currently using angular but applies equally to vanilla js
   $scope.searchSuggestion = function() {
        this.state.searchText = this.state.suggestion;
        this.submit();
    };

理想的测试代码:

it('should set the searchText to be the suggestion', function(){
        // arrange
        sinon.stub(scope, 'submit');
        scope.state.searchText = 'old value';
        scope.state.suggestion = 'new value';
        // act
        scope.searchSuggestion();
        // assert
        expect(scope.submit.called).to.be(true) 
        // ~not sure how to see if searchText was set first
    });

我刚刚处理了一个类似的问题,所以尽管这是一个相当古老的问题,但我还是回答了。

对我有效的方法是用一个做断言的函数来代替这个函数,所以类似这样的东西:

it('should set the searchText to be the suggestion', function(){
    scope.state.searchText = 'old value';
    scope.state.suggestion = 'new value';
    scope.submit = function() {
      expect(whatever).to.equal(somethingElse);
    };
    scope.searchSuggestion();
});

这样,当调用submit时,您可以使用所需的任何断言来检查前提条件。不利的一面是,您可能需要添加一些额外的代码来处理恢复原始函数的问题,如果从未调用过该函数,则测试将顺利通过,因此您可能需要向其添加done()回调,以防万一。