Skip to content

Commit

Permalink
Add pagehide forcing for web vital metrics
Browse files Browse the repository at this point in the history
This brings back the hack we removed from PR #949. I've also added a
test for it. When we remove the hack, the test fails, otherwise passes.
  • Loading branch information
inancgumus authored and ka3de committed Jul 11, 2023
1 parent a9bbb79 commit a8ebe8c
Showing 3 changed files with 52 additions and 0 deletions.
4 changes: 4 additions & 0 deletions common/page.go
Original file line number Diff line number Diff line change
@@ -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)
Empty file removed tests/static/empty.html
Empty file.
48 changes: 48 additions & 0 deletions tests/webvital_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}

0 comments on commit a8ebe8c

Please sign in to comment.