【问题标题】:chromeLauncher/Lighthouse: Mocking chained dependencies that return promises using JestchromeLauncher/Lighthouse:使用 Jest 模拟返回承诺的链式依赖项
【发布时间】:2018-11-18 20:01:17
【问题描述】:

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

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

在进行测试的过程中,我发现由 Lighthouse 调用的 chrome-launcher 会在我进行 Jest 测试时启动。这意味着我没有正确地嘲笑这种依赖。我认为模拟 Lighthouse 就足够了,并且已经这样做了,但我对如何模拟“thennable”chrome 启动器功能感到困惑。

下面的 launchChromeAndRunLighthouse 函数来自 Lighthouse Node 文档。

灯塔.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 使其无法启动感到困惑。谢谢

【问题讨论】:

    标签: node.js unit-testing jestjs lighthouse


    【解决方案1】:

    您不需要模拟 chromeLauncher,让它像它一样工作。仅仅模拟灯塔就足以让测试运行并通过。它在我的项目中按预期工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-14
      • 1970-01-01
      • 2020-10-07
      • 1970-01-01
      • 1970-01-01
      • 2020-07-30
      • 1970-01-01
      相关资源
      最近更新 更多