javascript - Stubbing a nested function in Jest
问题描述
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?
解决方案
利用sinon
在测试b
时,您应该测试它对来自a
(快乐和失败流)的不同响应的行为。因此,您需要a
使用不同的返回来进行存根以b
正确测试。
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'
我还没有测试过这段代码,所以如果您需要了解更多关于 sinon 存根的信息,请参考官方文档。
推荐阅读
- java - 我无法打开 OMNeT++ IDE
- angular - 如何在 Typescript 中动态禁用或启用 ng-multiselect-dropdown
- python - sqlalchemy 等价于 sql 语法
- php - 在路由组中分配中间件和在控制器的构造函数中启动它有什么区别吗?
- php - 使用imagick从PDF创建图像时出现以下错误,任何人都可以帮助修复它
- javascript - webpack 4 给出背景: url([object Module]) as bg image
- jasmine - Uncaught ReferenceError: Zone is not defined (Jasmine)
- c# - 有没有办法用 linq 查询过滤嵌套列表,以便我最终得到充分过滤列表的过滤列表?
- google-cloud-platform - 在 dataproc 上提交 Presto 作业
- c# - Perlin 噪声波对 3d 球体的影响