首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >chromeLauncher/Lighthouse:使用Jest模拟返回承诺的链式依赖关系

chromeLauncher/Lighthouse:使用Jest模拟返回承诺的链式依赖关系
EN

Stack Overflow用户
提问于 2018-11-19 04:01:18
回答 1查看 170关注 0票数 1

我有一个应用程序,其中包含一个节点脚本,该脚本以编程方式和无目的(Lighthouse documentation)运行Lighthouse v3来测试应用程序的性能。

我为此编写了一些Jest测试,这些测试在本地通过。测试不是测试灯塔本身,而是测试Node脚本如何处理从灯塔返回的结果数据。因此,必须对灯塔依赖项进行模拟。

在我做测试的过程中,我发现由灯塔调用的chrome-launcher会在我进行Jest测试时启动。这意味着我没有正确地模拟这个依赖关系。我认为模拟灯塔已经足够了,但我不知道如何才能模拟'thennable‘chrome launcher函数。

下面的launchChromeAndRunLighthouse函数来自灯塔节点文档。

lighthouse.js

代码语言:javascript
运行
复制
    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

代码语言:javascript
运行
复制
    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而感到困惑,因此它无法启动。谢谢

EN

回答 1

Stack Overflow用户

发布于 2021-02-06 21:18:34

你不需要嘲笑chromeLauncher,让它原封不动地工作。仅仅模拟灯塔就足以让测试运行并通过测试。它在我的项目中按照预期工作。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53364894

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档