0

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

当我手动测试我的库,打开浏览器并修改文件时,,页面会刷新(通过注入的代码,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

4

1 回答 1

0

测试失败是因为注释下方的最后一部分\\ 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 );

});
于 2019-06-04T15:04:59.217 回答