How to spy on amplify request and publish with jasmine?

360 views Asked by At

I'm testing code that uses amplify, I'm having trouble verifying what happens with both request and publish when they're both used in the subject under test.

it("should put an updated entity on save", function () {
    spyOn(amplify, 'publish');
    spyOn(amplify, 'request');

    viewModel.save();

    expect(amplify.publish.argsForCall).toEqual([['foo']]);
    expect(amplify.request.argsForCall).toEqual([['bar']]);
});

How ever I construct a test in this fashion argsForCall on one of these always ends up as undefined.

In a similar test:

spyOn(amplify, 'request');
spyOn(amplify, 'publish');

viewModel.cancel();

expect(amplify.request).not.toHaveBeenCalled();
expect(amplify.publish.mostRecentCall.args).toEqual(['baz']);

I don't have issues with multiple usages of spyOn. However it seems like the arguments recording is captured to a single function?

How can I verify these actions?

I did try something like jasmine.createSpyObj('amplify', ['request', 'publish']); but this didn't help me at all and my arguments were never defined or what I expected (I don't recall exactly, I just know I got no where with this syntax).

1

There are 1 answers

0
Chris Marisic On BEST ANSWER

So it seems like I was suffering from an intersection of issues. Using Karma the version of Jasmine it is based off uses Jasmine 1.x while the documentation page was 2.x My needs really revolved around the andCallThrough()

Code relevant to 1.x

spyOn(amplify, 'publish').andCallThrough();
spyOn(amplify, 'request');

viewModel.save();

expect(amplify.publish.calls[0].args).toEqual(['event-1']);
expect(amplify.publish.calls[1].args).toEqual(['event-2']);
expect(amplify.request.mostRecentCall.args[0].resourceId)
           .toEqual('my-resource-id-value');

Code relevant 2.x (untested)

spyOn(amplify, 'publish').and.callThrough();
spyOn(amplify, 'request');

viewModel.save();

expect(amplify.publish.calls.argsFor(0)).toEqual(['event-1']);
expect(amplify.publish.calls.argsFor(1)).toEqual(['event-2']);
expect(amplify.request.calls.mostRecent().args[0].resourceId)
           .toEqual('my-resource-id-value');