簡體   English   中英

chromeLauncher/Lighthouse:模擬使用 Jest 返回承諾的鏈式依賴項

[英]chromeLauncher/Lighthouse: Mocking chained dependencies that return promises using Jest

我有一個應用程序,其中包含一個 Node 腳本,該腳本以編程方式和無頭( Lighthouse 文檔)運行 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;

燈塔.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 感到困惑,因此它無法啟動。 謝謝

你不需要模擬 chromeLauncher,讓它像它一樣工作。 僅僅嘲笑燈塔就足以讓測試運行並通過。 它在我的項目中按預期工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM