diff --git a/common/page.go b/common/page.go index 1e22ccc59..57d469427 100644 --- a/common/page.go +++ b/common/page.go @@ -425,6 +425,10 @@ func (p *Page) Click(selector string, opts goja.Value) error { func (p *Page) Close(opts goja.Value) error { p.logger.Debugf("Page:Close", "sid:%v", p.sessionID()) + // forcing the pagehide event to trigger web vitals metrics. + v := p.vu.Runtime().ToValue(`() => window.dispatchEvent(new Event('pagehide'))`) + _ = p.Evaluate(v) + add := runtime.RemoveBinding(webVitalBinding) if err := add.Do(cdp.WithExecutor(p.ctx, p.session)); err != nil { return fmt.Errorf("internal error while removing binding from page: %w", err) diff --git a/tests/static/empty.html b/tests/static/empty.html deleted file mode 100644 index e69de29bb..000000000 diff --git a/tests/webvital_test.go b/tests/webvital_test.go index f987b1d6c..e0c1988bc 100644 --- a/tests/webvital_test.go +++ b/tests/webvital_test.go @@ -72,3 +72,51 @@ func TestWebVitalMetric(t *testing.T) { assert.True(t, v, "expected %s to have been measured and emitted", k) } } + +func TestWebVitalMetricNoInteraction(t *testing.T) { + var ( + samples = make(chan k6metrics.SampleContainer) + browser = newTestBrowser(t, withFileServer(), withSamples(samples)) + expected = map[string]bool{ + "browser_web_vital_ttfb": false, + "browser_web_vital_fcp": false, + "browser_web_vital_lcp": false, + "browser_web_vital_cls": false, + } + ) + + done := make(chan struct{}) + ctx, cancel := context.WithTimeout(browser.context(), 5*time.Second) + defer cancel() + go func() { + for { + var metric k6metrics.SampleContainer + select { + case <-done: + return + case <-ctx.Done(): + return + case metric = <-samples: + } + samples := metric.GetSamples() + for _, s := range samples { + if _, ok := expected[s.Metric.Name]; ok { + expected[s.Metric.Name] = true + } + } + } + }() + + page := browser.NewPage(nil) + resp, err := page.Goto(browser.staticURL("/web_vitals.html"), nil) + require.NoError(t, err) + require.NotNil(t, resp) + + // prevents `err:fetching response body: context canceled` warning.` + require.NoError(t, page.Close(nil)) + done <- struct{}{} + + for k, v := range expected { + assert.True(t, v, "expected %s to have been measured and emitted", k) + } +}