Stubbing a nested function in Jest










2














I have two functions in a module at the module scope. One of the functions is used by another.



async function allCinemas( puppeteer, states ) 
const cinemaDetails = ;
const page = await puppeteer
.launch(
handleSIGINT: true /*devtools: false,headless: true*/
)
.then(browser => browser.newPage());

await page.setViewport( width: 1366, height: 735 ); //form factor - laptop/PC
await page.goto("https://www.somesite.come");

for (const state of states)
const res = await cinemasfromState(page, state);
res.forEach(cin =>
cinemaDetails.push(cin);
);

await page.close();

return cinemaDetails;


async function cinemasfromState(page, state)
const CINEMA_SELECTOR = `div[$[STATE]] div.top-select-option h.element`;

let res = await page.evaluate(
(elementPath, state) =>
let results = Array.from(document.querySelectorAll(elementPath)).map(
function(cin, index)
let result =
cinemaState: this.state,
cinemaId: cin.getAttribute("id"),
cinemaName: cin.getAttribute("name"),
;
return result;
,
state
);

return [...results.reduce((a, c) => a.set(c.cinemaId, c), new Map()).values()];

,
CINEMA_SELECTOR.replace("$[STATE]", state),
state
);

return Promise.resolve(res);

export allCinemas, cinemasfromState ;


I have separately tested function cinemasfromState



Therefore when I test function allCinemas, I am thinking of stubbing function cinemasfromState.



How can I not stub/mock cinemasfromState so that I don’t have to duplicate testing?










share|improve this question























  • Could you please add more precise code snippet. This one is missing the export statements so its quite hard to get say how to mock something.
    – Andreas Köberle
    Nov 12 '18 at 8:59










  • @AndreasKöberle, apologies for the brevity.. code updated
    – Theepan Thevathasasn
    Nov 12 '18 at 11:47















2














I have two functions in a module at the module scope. One of the functions is used by another.



async function allCinemas( puppeteer, states ) 
const cinemaDetails = ;
const page = await puppeteer
.launch(
handleSIGINT: true /*devtools: false,headless: true*/
)
.then(browser => browser.newPage());

await page.setViewport( width: 1366, height: 735 ); //form factor - laptop/PC
await page.goto("https://www.somesite.come");

for (const state of states)
const res = await cinemasfromState(page, state);
res.forEach(cin =>
cinemaDetails.push(cin);
);

await page.close();

return cinemaDetails;


async function cinemasfromState(page, state)
const CINEMA_SELECTOR = `div[$[STATE]] div.top-select-option h.element`;

let res = await page.evaluate(
(elementPath, state) =>
let results = Array.from(document.querySelectorAll(elementPath)).map(
function(cin, index)
let result =
cinemaState: this.state,
cinemaId: cin.getAttribute("id"),
cinemaName: cin.getAttribute("name"),
;
return result;
,
state
);

return [...results.reduce((a, c) => a.set(c.cinemaId, c), new Map()).values()];

,
CINEMA_SELECTOR.replace("$[STATE]", state),
state
);

return Promise.resolve(res);

export allCinemas, cinemasfromState ;


I have separately tested function cinemasfromState



Therefore when I test function allCinemas, I am thinking of stubbing function cinemasfromState.



How can I not stub/mock cinemasfromState so that I don’t have to duplicate testing?










share|improve this question























  • Could you please add more precise code snippet. This one is missing the export statements so its quite hard to get say how to mock something.
    – Andreas Köberle
    Nov 12 '18 at 8:59










  • @AndreasKöberle, apologies for the brevity.. code updated
    – Theepan Thevathasasn
    Nov 12 '18 at 11:47













2












2








2







I have two functions in a module at the module scope. One of the functions is used by another.



async function allCinemas( puppeteer, states ) 
const cinemaDetails = ;
const page = await puppeteer
.launch(
handleSIGINT: true /*devtools: false,headless: true*/
)
.then(browser => browser.newPage());

await page.setViewport( width: 1366, height: 735 ); //form factor - laptop/PC
await page.goto("https://www.somesite.come");

for (const state of states)
const res = await cinemasfromState(page, state);
res.forEach(cin =>
cinemaDetails.push(cin);
);

await page.close();

return cinemaDetails;


async function cinemasfromState(page, state)
const CINEMA_SELECTOR = `div[$[STATE]] div.top-select-option h.element`;

let res = await page.evaluate(
(elementPath, state) =>
let results = Array.from(document.querySelectorAll(elementPath)).map(
function(cin, index)
let result =
cinemaState: this.state,
cinemaId: cin.getAttribute("id"),
cinemaName: cin.getAttribute("name"),
;
return result;
,
state
);

return [...results.reduce((a, c) => a.set(c.cinemaId, c), new Map()).values()];

,
CINEMA_SELECTOR.replace("$[STATE]", state),
state
);

return Promise.resolve(res);

export allCinemas, cinemasfromState ;


I have separately tested function cinemasfromState



Therefore when I test function allCinemas, I am thinking of stubbing function cinemasfromState.



How can I not stub/mock cinemasfromState so that I don’t have to duplicate testing?










share|improve this question















I have two functions in a module at the module scope. One of the functions is used by another.



async function allCinemas( puppeteer, states ) 
const cinemaDetails = ;
const page = await puppeteer
.launch(
handleSIGINT: true /*devtools: false,headless: true*/
)
.then(browser => browser.newPage());

await page.setViewport( width: 1366, height: 735 ); //form factor - laptop/PC
await page.goto("https://www.somesite.come");

for (const state of states)
const res = await cinemasfromState(page, state);
res.forEach(cin =>
cinemaDetails.push(cin);
);

await page.close();

return cinemaDetails;


async function cinemasfromState(page, state)
const CINEMA_SELECTOR = `div[$[STATE]] div.top-select-option h.element`;

let res = await page.evaluate(
(elementPath, state) =>
let results = Array.from(document.querySelectorAll(elementPath)).map(
function(cin, index)
let result =
cinemaState: this.state,
cinemaId: cin.getAttribute("id"),
cinemaName: cin.getAttribute("name"),
;
return result;
,
state
);

return [...results.reduce((a, c) => a.set(c.cinemaId, c), new Map()).values()];

,
CINEMA_SELECTOR.replace("$[STATE]", state),
state
);

return Promise.resolve(res);

export allCinemas, cinemasfromState ;


I have separately tested function cinemasfromState



Therefore when I test function allCinemas, I am thinking of stubbing function cinemasfromState.



How can I not stub/mock cinemasfromState so that I don’t have to duplicate testing?







javascript unit-testing jestjs






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 12 '18 at 11:47







Theepan Thevathasasn

















asked Nov 12 '18 at 4:36









Theepan ThevathasasnTheepan Thevathasasn

5819




5819











  • Could you please add more precise code snippet. This one is missing the export statements so its quite hard to get say how to mock something.
    – Andreas Köberle
    Nov 12 '18 at 8:59










  • @AndreasKöberle, apologies for the brevity.. code updated
    – Theepan Thevathasasn
    Nov 12 '18 at 11:47
















  • Could you please add more precise code snippet. This one is missing the export statements so its quite hard to get say how to mock something.
    – Andreas Köberle
    Nov 12 '18 at 8:59










  • @AndreasKöberle, apologies for the brevity.. code updated
    – Theepan Thevathasasn
    Nov 12 '18 at 11:47















Could you please add more precise code snippet. This one is missing the export statements so its quite hard to get say how to mock something.
– Andreas Köberle
Nov 12 '18 at 8:59




Could you please add more precise code snippet. This one is missing the export statements so its quite hard to get say how to mock something.
– Andreas Köberle
Nov 12 '18 at 8:59












@AndreasKöberle, apologies for the brevity.. code updated
– Theepan Thevathasasn
Nov 12 '18 at 11:47




@AndreasKöberle, apologies for the brevity.. code updated
– Theepan Thevathasasn
Nov 12 '18 at 11:47












2 Answers
2






active

oldest

votes


















0














As long as both function are defined in the same module there is no sane way to mock only one function that is then used by the other function is the module. Maybe it becomes clear why if you think about the order the code is executed.



  1. Inside the module the two functions A and B are declared. Function B has reference to function A.

  2. The module is imported into your test. At this point in time there is no way to remove the reference to A inside of B.

So the only solution to test this two functions with mocking one of them is to put them in differnt modules, as you can easily mock one of them in the test. As you export both of them it should be quite easy to put them in different modules.






share|improve this answer




















  • Cool. If I do that, could you please recommend a code skeleton organise the test ?
    – Theepan Thevathasasn
    Nov 12 '18 at 21:38


















2














Use sinon



While testing b, you should test for its behavior on different responses from a (happy and fail flows). So you need to stub a with different returns to test b correctly.



import * as allMethods from './whereever-the-file-is';
import sinon from 'sinon';

// inside your test case
const aStub = sinon.stub(allMethods, 'a');

aStub.returns('x');
// test your function b on what it should do when a returns 'x'

aStub.returns('y');
// test your function b on what it should do when a returns 'y'


I haven't tested this code, so pl refer to official docs if you need to know more about sinon stubs.






share|improve this answer




















  • Are you that this will work. The only think it does is to overwrite a in the context of your imported allMethods variable in the test. This will not affect the one that is used by b in the file itself.
    – Andreas Köberle
    Nov 12 '18 at 8:58










  • @Dinesh, would be great if you could help me understand how this will help me intercept the code?
    – Theepan Thevathasasn
    Nov 12 '18 at 11:49










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53256031%2fstubbing-a-nested-function-in-jest%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














As long as both function are defined in the same module there is no sane way to mock only one function that is then used by the other function is the module. Maybe it becomes clear why if you think about the order the code is executed.



  1. Inside the module the two functions A and B are declared. Function B has reference to function A.

  2. The module is imported into your test. At this point in time there is no way to remove the reference to A inside of B.

So the only solution to test this two functions with mocking one of them is to put them in differnt modules, as you can easily mock one of them in the test. As you export both of them it should be quite easy to put them in different modules.






share|improve this answer




















  • Cool. If I do that, could you please recommend a code skeleton organise the test ?
    – Theepan Thevathasasn
    Nov 12 '18 at 21:38















0














As long as both function are defined in the same module there is no sane way to mock only one function that is then used by the other function is the module. Maybe it becomes clear why if you think about the order the code is executed.



  1. Inside the module the two functions A and B are declared. Function B has reference to function A.

  2. The module is imported into your test. At this point in time there is no way to remove the reference to A inside of B.

So the only solution to test this two functions with mocking one of them is to put them in differnt modules, as you can easily mock one of them in the test. As you export both of them it should be quite easy to put them in different modules.






share|improve this answer




















  • Cool. If I do that, could you please recommend a code skeleton organise the test ?
    – Theepan Thevathasasn
    Nov 12 '18 at 21:38













0












0








0






As long as both function are defined in the same module there is no sane way to mock only one function that is then used by the other function is the module. Maybe it becomes clear why if you think about the order the code is executed.



  1. Inside the module the two functions A and B are declared. Function B has reference to function A.

  2. The module is imported into your test. At this point in time there is no way to remove the reference to A inside of B.

So the only solution to test this two functions with mocking one of them is to put them in differnt modules, as you can easily mock one of them in the test. As you export both of them it should be quite easy to put them in different modules.






share|improve this answer












As long as both function are defined in the same module there is no sane way to mock only one function that is then used by the other function is the module. Maybe it becomes clear why if you think about the order the code is executed.



  1. Inside the module the two functions A and B are declared. Function B has reference to function A.

  2. The module is imported into your test. At this point in time there is no way to remove the reference to A inside of B.

So the only solution to test this two functions with mocking one of them is to put them in differnt modules, as you can easily mock one of them in the test. As you export both of them it should be quite easy to put them in different modules.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 12 '18 at 19:37









Andreas KöberleAndreas Köberle

47.6k39177235




47.6k39177235











  • Cool. If I do that, could you please recommend a code skeleton organise the test ?
    – Theepan Thevathasasn
    Nov 12 '18 at 21:38
















  • Cool. If I do that, could you please recommend a code skeleton organise the test ?
    – Theepan Thevathasasn
    Nov 12 '18 at 21:38















Cool. If I do that, could you please recommend a code skeleton organise the test ?
– Theepan Thevathasasn
Nov 12 '18 at 21:38




Cool. If I do that, could you please recommend a code skeleton organise the test ?
– Theepan Thevathasasn
Nov 12 '18 at 21:38













2














Use sinon



While testing b, you should test for its behavior on different responses from a (happy and fail flows). So you need to stub a with different returns to test b correctly.



import * as allMethods from './whereever-the-file-is';
import sinon from 'sinon';

// inside your test case
const aStub = sinon.stub(allMethods, 'a');

aStub.returns('x');
// test your function b on what it should do when a returns 'x'

aStub.returns('y');
// test your function b on what it should do when a returns 'y'


I haven't tested this code, so pl refer to official docs if you need to know more about sinon stubs.






share|improve this answer




















  • Are you that this will work. The only think it does is to overwrite a in the context of your imported allMethods variable in the test. This will not affect the one that is used by b in the file itself.
    – Andreas Köberle
    Nov 12 '18 at 8:58










  • @Dinesh, would be great if you could help me understand how this will help me intercept the code?
    – Theepan Thevathasasn
    Nov 12 '18 at 11:49















2














Use sinon



While testing b, you should test for its behavior on different responses from a (happy and fail flows). So you need to stub a with different returns to test b correctly.



import * as allMethods from './whereever-the-file-is';
import sinon from 'sinon';

// inside your test case
const aStub = sinon.stub(allMethods, 'a');

aStub.returns('x');
// test your function b on what it should do when a returns 'x'

aStub.returns('y');
// test your function b on what it should do when a returns 'y'


I haven't tested this code, so pl refer to official docs if you need to know more about sinon stubs.






share|improve this answer




















  • Are you that this will work. The only think it does is to overwrite a in the context of your imported allMethods variable in the test. This will not affect the one that is used by b in the file itself.
    – Andreas Köberle
    Nov 12 '18 at 8:58










  • @Dinesh, would be great if you could help me understand how this will help me intercept the code?
    – Theepan Thevathasasn
    Nov 12 '18 at 11:49













2












2








2






Use sinon



While testing b, you should test for its behavior on different responses from a (happy and fail flows). So you need to stub a with different returns to test b correctly.



import * as allMethods from './whereever-the-file-is';
import sinon from 'sinon';

// inside your test case
const aStub = sinon.stub(allMethods, 'a');

aStub.returns('x');
// test your function b on what it should do when a returns 'x'

aStub.returns('y');
// test your function b on what it should do when a returns 'y'


I haven't tested this code, so pl refer to official docs if you need to know more about sinon stubs.






share|improve this answer












Use sinon



While testing b, you should test for its behavior on different responses from a (happy and fail flows). So you need to stub a with different returns to test b correctly.



import * as allMethods from './whereever-the-file-is';
import sinon from 'sinon';

// inside your test case
const aStub = sinon.stub(allMethods, 'a');

aStub.returns('x');
// test your function b on what it should do when a returns 'x'

aStub.returns('y');
// test your function b on what it should do when a returns 'y'


I haven't tested this code, so pl refer to official docs if you need to know more about sinon stubs.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 12 '18 at 5:42









Dinesh PandiyanDinesh Pandiyan

2,465925




2,465925











  • Are you that this will work. The only think it does is to overwrite a in the context of your imported allMethods variable in the test. This will not affect the one that is used by b in the file itself.
    – Andreas Köberle
    Nov 12 '18 at 8:58










  • @Dinesh, would be great if you could help me understand how this will help me intercept the code?
    – Theepan Thevathasasn
    Nov 12 '18 at 11:49
















  • Are you that this will work. The only think it does is to overwrite a in the context of your imported allMethods variable in the test. This will not affect the one that is used by b in the file itself.
    – Andreas Köberle
    Nov 12 '18 at 8:58










  • @Dinesh, would be great if you could help me understand how this will help me intercept the code?
    – Theepan Thevathasasn
    Nov 12 '18 at 11:49















Are you that this will work. The only think it does is to overwrite a in the context of your imported allMethods variable in the test. This will not affect the one that is used by b in the file itself.
– Andreas Köberle
Nov 12 '18 at 8:58




Are you that this will work. The only think it does is to overwrite a in the context of your imported allMethods variable in the test. This will not affect the one that is used by b in the file itself.
– Andreas Köberle
Nov 12 '18 at 8:58












@Dinesh, would be great if you could help me understand how this will help me intercept the code?
– Theepan Thevathasasn
Nov 12 '18 at 11:49




@Dinesh, would be great if you could help me understand how this will help me intercept the code?
– Theepan Thevathasasn
Nov 12 '18 at 11:49

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53256031%2fstubbing-a-nested-function-in-jest%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Use pre created SQLite database for Android project in kotlin

Darth Vader #20

Ondo