我有一个应用程序,其中包含一个节点脚本,该脚本以编程方式和无目的(Lighthouse documentation)运行Lighthouse v3来测试应用程序的性能。
我为此编写了一些Jest测试,这些测试在本地通过。测试不是测试灯塔本身,而是测试Node脚本如何处理从灯塔返回的结果数据。因此,必须对灯塔依赖项进行模拟。
在我做测试的过程中,我发现由灯塔调用的chrome-launcher会在我进行Jest测试时启动。这意味着我没有正确地模拟这个依赖关系。我认为模拟灯塔已经足够了,但我不知道如何才能模拟'thennable‘chrome launcher函数。
下面的launchChromeAndRunLighthouse
函数来自灯塔节点文档。
lighthouse.js
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
function launchChromeAndRunLighthouse(url, opts, lConfig = null) {
return chromeLauncher
.launch({ chromeFlags: opts.chromeFlags })
.then(chrome => {
const options = { ...opts, port: chrome.port };
return lighthouse(url, options, lConfig).then(results =>
chrome.kill().then(() => results.lhr),
);
});
}
function myFunc(config) {
launchChromeAndRunLighthouse(myAppUrl, config);
// manipulates data returned from launchChromeAndRunLighthouse
return true;
}
module.exports = myFunc;
lighthouse.test.js
import myFunc from './lighthouse';
jest.mock('lighthouse', () =>
jest.fn().mockResolvedValue({
lhr: {
categories: {
performance: {
id: 'performance',
score: 1,
}
},
},
}),
);
// chromeLauncher actually gets invoked by this
describe('myfunc', () => {
it('tests myfunc', async () => {
const result = await myFunc(config);
expect(result).toEqual(true);
});
});
刚刚接触Jest,我对如何模拟chromeLauncher而感到困惑,因此它无法启动。谢谢
发布于 2021-02-06 21:18:34
你不需要嘲笑chromeLauncher,让它原封不动地工作。仅仅模拟灯塔就足以让测试运行并通过测试。它在我的项目中按照预期工作。
https://stackoverflow.com/questions/53364894
复制相似问题