Unit testing Knockout Computed values

779 views
Skip to first unread message

bcorr...@gmail.com

unread,
May 28, 2013, 10:35:05 PM5/28/13
to knock...@googlegroups.com

I'm trying to write a test for a ko.computed field that is dependent on two other complex computeds (removed here for demonstration).

function PositionsViewModel(options) {
  var self = this;
  self.computed1 = ko.computed(function() { return 1; });
  self.computed2 = ko.computed(function() { return 2; });
  self.computedIWantToTest = ko.computed(function() { 
    return self.computed1() + self.computed2();
  });
}

In my jasmine test I create an instance of the VM in a beforeEach like so:

this.subject = new PositionsViewModel();

I want to be able to stub computed1 and computed2 so that I may test computedIWantToTest in isolation. So far my attempts to do so have failed.

What I'd like to do:

spyOn(subject,computed2).andReturn(5);
subject.computedIWantToTest.update(true);

It appears that dependentObservables at one point computed has a notifySubscribers method, but it was removed when computeds were introduced.  If that still existed I could do:

var originalComputed = subject.computed2;
spyOn(subject,computed2).andReturn(5);
subject.originalComputed.notifySubscribers(true);

Is there a better way to do this?

bcorr...@gmail.com

unread,
May 30, 2013, 9:55:52 PM5/30/13
to knock...@googlegroups.com, bcorr...@gmail.com

Ok, so I got this to work, though I hate myself for this. I really think Knockout should expose the evaluateImmediately method publicly, and I'm going to link a pull to do so.

Here's my solution:

p = new PositionsViewModel();
originalComputed = p.redApples; spyOn(p,'computed1').andReturn(5);
originalComputed.notifySubscribers(); expect(p. computedIWantToTest
()).toBe(7);

Kijana Woodard

unread,
May 30, 2013, 10:37:54 PM5/30/13
to knock...@googlegroups.com, bcorr...@gmail.com

Does valueHasMutated apply here?
http://stackoverflow.com/questions/8537397/knockout-js-how-to-force-view-refresh-instead-of-using-ko-observable

--
You received this message because you are subscribed to the Google Groups "KnockoutJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email to knockoutjs+...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Brian Corrigan

unread,
May 30, 2013, 11:35:50 PM5/30/13
to Kijana Woodard, knock...@googlegroups.com
In this we're trying to mock one computed that is a dependency of a second.  valueHasMutated is only available for simple observables.  :(
Reply all
Reply to author
Forward
0 new messages