Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Jasmine spies on an object created inside another method?

Given the following code snippet, how would you create a Jasmine spyOn test to confirm that doSomething gets called when you run MyFunction?

function MyFunction() {
    var foo = new MyCoolObject();
    foo.doSomething();
};

Here's what my test looks like. Unfortunately, I get an error when the spyOn call is evaluated:

describe("MyFunction", function () {
    it("calls doSomething", function () {

        spyOn(MyCoolObject, "doSomething");
        MyFunction();
        expect(MyCoolObject.doSomething).toHaveBeenCalled();

    });
});

Jasmine doesn't appear to recognize the doSomething method at that point. Any suggestions?

like image 718
thinkbigthinksmall Avatar asked Mar 10 '14 03:03

thinkbigthinksmall


People also ask

How do you use parameters in spyOn method?

spyOn() takes two parameters: the first parameter is the name of the object and the second parameter is the name of the method to be spied upon. It replaces the spied method with a stub, and does not actually execute the real method. The spyOn() function can however be called only on existing methods.

Which of the following is used for spying function in Jasmine?

spyOn() spyOn() is inbuilt into the Jasmine library which allows you to spy on a definite piece of code.

How do you mock a method in Jasmine?

Using Jasmine spies to mock code Jasmine spies are easy to set up. You set the object and function you want to spy on, and that code won't be executed. In the code below, we have a MyApp module with a flag property and a setFlag() function exposed. We also have an instance of that module called myApp in the test.


1 Answers

Alternatively, as Gregg hinted, we could work with 'prototype'. That is, instead of spying on MyCoolObject directly, we can spy on MyCoolObject.prototype.

describe("MyFunction", function () {
    it("calls doSomething", function () {
        spyOn(MyCoolObject.prototype, "doSomething");
        MyFunction();
        expect(MyCoolObject.prototype.doSomething).toHaveBeenCalled();

    });
});
like image 53
hyong Avatar answered Oct 03 '22 14:10

hyong