Testing a function which uses a promise.

207 views
Skip to first unread message

Patrick Davey

unread,
Jul 8, 2016, 9:53:42 AM7/8/16
to Jasmine
Hi there,

I'm a little new to JavaScript testing so this may be quite the wrong approach to testing. With that said ;)

I'm using vue-js and vue-resource (https://github.com/vuejs/vue-resource/) . The code I'm trying to test (a vue-js component) has a download function which looks like this:

    download: function() {
      this.$http.post('/items/' + this.cast.id + '/download.json')
        .then(response => {
          this.cast.state = 'downloading'
        }, error => {
          this.error = 'Could not fetch casts from server!'
        })
    }


I am mocking out the post in my test, but I can't work out how to assert _after_ the "then" has returned. I am using Jasmine2, and I have tried passing the `done` callback around - but still, I'm missing something.

    it('should change the state to downloading if download called', () => {
      <snip, setup for intercepting the ajax call>

      testComponent.download()

      // how to ensure that the "then" has been called (and state changed) before moving on to the assert?

      expect(testComponent.cast.state).toBe('downloading');
    });
  });

If I add in console.logs I can see that the "then" part is being called after the call to "expect"

 Apologies if this betrays some basic misunderstanding of how to test - but pointers would be really appreciated. I've seen quite a few examples of testing promises themselves, but all I really want to do is to call a method and wait until the promise has been fulfilled.

Thanks!
Patrick

Gregg Van Hove

unread,
Aug 8, 2016, 12:48:21 PM8/8/16
to jasmi...@googlegroups.com
Some of the specifics of ensuring the promise is complete depend on the particular promise library or how you are mocking it out. The way that I have seen this work best is to use some kind of mock promise (see: https://github.com/charleshansen/mock-promises for an example library). This allows the test to specify how the promise behaves so it can ensure that the proper path is followed for what you're trying to assert.

Hope this helps. Thanks for using Jasmine!

-Gregg

--
You received this message because you are subscribed to the Google Groups "Jasmine" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jasmine-js+unsubscribe@googlegroups.com.
To post to this group, send email to jasmi...@googlegroups.com.
Visit this group at https://groups.google.com/group/jasmine-js.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages