I’m doing some testing with the Jasmine framework and I want to spy on a pub sub publish method that I’m using. However, the publish method is firing twice and I only want to spy on it the second time. I tried to just copy the publish method to another method and then spy on the original method, like so:
pubsub.publishCopy = pubsub.publish;
spyOn(pubsub, "publish");
// this call has another call to pubsub.publish. it is this
// 2nd pub sub call that I want to spy on
pubsub.publishCopy(args);
// this shows an error because the pubsub.publishCopy is 'pointing to
// pubsub.publish instead of being a new function with the same functionality
expect(pubsub.publish).toHaveBeenCalledWith(differentArgs);
However, all I’m doing is just referencing the pubsub.publish method when I call pubsub.publishCopy which throws an error in my test. How would I copy the publish method correctly to suit my needs?
You can try
It’s basically wrapping the original method in a brand-new method, instead of simply creating an extra reference to the original function object.
No idea if it’ll work, though – haven’t worked with Jasmine