Nimmo
Nimmo

Reputation: 105

Sinon stub returns false

I am doing testing using sinon and ava. I am stubbing some functions and checking these functions are getting called or not. I have checked the console, function are getting called. But instead sinon returns it as notCalled(.called as false). Below is the piece of code.

const test = (a, b) => {

transformer.getActivity(a, b).then((response) => {

    var response = JSON.parse(response);
    var data = response.data;


    getToken.getToken(testData.organizationId).then(token => {
        let requestData = {
            url: url,
            token: token
        }
        return utils.axiosGetRequest(requestData);
    }).catch(error => {
        console.log("Error: ", error);

    });
})

};

test('test',(t)=>{
const transformerStub =  sandbox.stub(transformer,'getActivity').resolves(JSON.stringify({"componentTypeID":1234}));
const getAuthTokenStub = sandbox.stub(getToken,'getToken').resolves({"Token":"Value"});
const axiosGetRequest = sandbox.stub(utils,'axiosGetRequest');
app.test(organizationId,learning);
t.is(transformerStub.called,true); // it is getting called . it works well and returns true
t.is(getAuthTokenStub.called,true);  // it is getting called but returns false
t.is(axiosGetRequest.called,true);   // it is getting called but returns false

});

Upvotes: 1

Views: 1395

Answers (1)

andreyunugro
andreyunugro

Reputation: 1116

When wrapping an existing function with a stub, the original function is not called. https://sinonjs.org/releases/latest/stubs/

When you stub transformer in the first place, getToken.getToken and utils.AxiosGetRequest will not get called because the real getActivity will not get called.

There are 2 alternatives:

  1. If you want only to check whether method get called, use spy. For example: When you want to stub util, use spy on getToken and transformer; when you want to stub getToken, use spy on transformer.
  2. If you still want to add behaviour (resolves) to all 3 in 1 test, you can rearrange your code. For example: stub utils, run app.test, do assertion; stub getToken, run app.test, do assertion; and finally stub transformer, run app.test, and do assertion.

Upvotes: 1

Related Questions