I am currently using sinon.js in for stubbing. It is possible to stub and spy on methods, but not properties using the library from what I could see.
In the following example, would there be a way to check that state.searchText
was set to state.suggestion
before submit
is called?
// currently using angular but applies equally to vanilla js
$scope.searchSuggestion = function() {
this.state.searchText = this.state.suggestion;
this.submit();
};
ideal testing code:
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
});
I was just dealing with a similar issue, so answering despite this being a pretty old Q.
The approach that worked for me was replacing the function with one that does an assertion, so something like this:
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();
});
This way when submit gets called, you can check preconditions using any assertion you want. Downside is you may have to add some extra code to handle restoring the original function back, and if the function never gets called, the test will pass without failure - so you may want to add a done()
callback to it just in case.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.