Spectron app.client.close() 不会触发 on('close' 事件



我有一个多窗口电子应用程序,即它由一个启动窗口和一个主窗口组成。

主进程负责首先显示启动器,在初始化所有内容后,它通过 ipc 获取事件并显示主窗口,隐藏启动器。

我在主窗口上使用on('close')来检测用户何时关闭主窗口,再次显示启动器并执行一些拆卸逻辑,完成后应用程序退出。

 this.mainWindow = new BrowserWindow({width: 1024, height: 768, webPreferences: {nodeIntegration: true}});
        this.mainWindow.setMenu(null);
        this.mainWindow.on('close', () => {
            this.logger.debug('"close" received');
            this.mainWindow.hide();
            this.launcherWindow.show();
            this.sendShutdown();
        });

这工作得很好,现在我想将这种行为与Spectron集成测试。我在向窗口发送关闭信号时遇到问题,模拟用户单击关闭。

it('should start shutting down the services gracefully if the user clicks on the close button', async () => {  
  await app.client.windowByIndex(1);
  await app.client.close();
  //..... expectations that verify the launcher window is visible now
});

我已经验证了索引为 1 的窗口是主窗口。当我调用app.client.close();时,主窗口关闭,但我可以在日志中看到主窗口的on('close', )事件未触发,因此它不会跳回到启动器。

我有什么遗漏/误解吗?

我最终将执行的代码包装在一个额外的方法中,并将该方法绑定到ipcMain.on("should-shutdown",..事件。无论如何,这是有道理的,因为其他渲染器也可以请求平稳关闭。

在Spectron测试中,我随后使用了

 const { ipcRenderer } = app.electron;
 ipcRenderer.send('smooth-shutdown');

而不是app.client.close()启动关机序列。

in main.js 添加波纹管代码

mainWindow.on('close', async function (event) {    
if(process.env.NODE_ENV=="test"){
  app.isQuiting = true;
  app.quit();
}
//other codes
})

在测试用例中添加NODE_ENV=测试

beforeAll(async function (done) {
    this.app = new Application({
        path: electronPath,
        chromeDriverArgs: ['--no-sandbox'],
        args: [path.join(__dirname, '../main.js')],
        env: {NODE_ENV: 'test'},
        waitTimeout: 10e2
    });
    
    await this.app.start()
    done();
})
afterAll(async function (done) {
    if (this.app && this.app.isRunning()) {
        await this.app.stop();            
        done();
    } else {
        done();
    }
})

最新更新