使用 Puppeteer 在 Jest 上重新加载后检查页面内容

Check the page's content after a reload on Jest with Puppeteer

我正在开发一个类似于 live-reload/browser-sync 的 nodejs 库,我正在使用 jest-puppeteer 进行自动化测试。

当我手动测试我的库,打开浏览器并修改文件时,voilá,页面刷新(通过注入的代码 运行 是 location.reload( true ) 当它通过 websocket 接收到信号时)。

但是当我 运行 使用 Jest 进行测试时,似乎 Puppeteer 没有得到刷新。

// "reloader" is my library
import reloader from './../src/index';

import * as fs              from 'fs';
import { promisify }        from 'util';

const read  = promisify( fs.readFile )
const write = promisify( fs.writeFile )

test('1. Refresh when file changes', async () => {

    const server  = await reloader( { dir: 'test/01' } );

    await page.goto( 'http://localhost:' + server.port );

    // This test passes
    await expect( page.title()).resolves.toMatch( 'Old title' );

    // Read and modify index.html to generate a refresh 
    const file    = 'test/01/index.html'
    const content = await read( file, 'utf8' );
    await write( file, content.replace( 'Old title', 'New title' ) );

    // Wait the page to refresh
    await page.waitForNavigation( { waitUntil: 'networkidle2' } )

    // This test doesn't pass
    // Still receiving "Old title" 
    await expect( page.title()).resolves.toMatch( 'New title' );

    // Undo the changes
    write( file, content );

});

在上次测试中,我没有收到 New title(在 index.html 文件中正确写入),而是收到 Old title

测试失败,因为评论 \ Undo the changes 下方的最后一部分不是 运行,并且测试文件保留在 New title

通过下面的测试,它完美地工作:

import reloader from './../src/index';

import * as fs              from 'fs';
import { promisify }        from 'util';

const read  = promisify( fs.readFile )
const write = promisify( fs.writeFile )

test('1. Refresh when file change', async () => {

    // If this test failed previously, lets guarantee that
    // everything is correct again before we begin
    const file    = 'test/01/index.html'
    const content = ( await read( file, 'utf8' ) ).replace( 'New title', 'Old title' );
    await write( file, content );

    const server  = await reloader( { dir: 'test/01' } );

    await page.goto( 'http://localhost:' + server.port );

    await expect( page.title()).resolves.toMatch( 'Old title' );

    // Read and modify index.html to generate a refresh 
    await write( file, content.replace( 'Old title', 'New title' ) );

    // Wait the page to refresh
    await page.waitForNavigation( { waitUntil: 'networkidle2' } )

    await expect( page.title()).resolves.toMatch( 'New title' );

    // Undo the changes
    write( file, content );

});