Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add async check util #13

Merged
merged 8 commits into from
Aug 16, 2024
Merged

Add async check util #13

merged 8 commits into from
Aug 16, 2024

Conversation

allansson
Copy link
Contributor

@allansson allansson commented Aug 13, 2024

What

This PR adds a version of the check function that makes working with async/await more ergonomic. It is drop-in compatible with the existing check function, i.e. using only sync values won't wrap results in a Promise. As an added bonus, it's also possible to skip passing the first value.

Why

Writing clean code using the standard check function is hard when using async code. To check a value you need to declare a temporary variable and await the value first:

const myVar = await res.json()

check(myVar, {
  'is Admin': () => myVar.isAdmin
})

This clutters the code with single use declarations and creates the need to make up bogus variable names.

Examples

// Sync
const a = check(res, {
  'as value': res.status === 200,
  'as func': res => res.headers['Content-Type'] === "application/json"
})

// Async
const b = await check(locator, {
  'as promise': locator.isChecked(),
  'as async func': l => l.getAttribute("draggable")
})

// Mixed
const c = await check(res, {
  'as value': true,
  'as promise': Promise.resolve(false)
})

EDIT: Removed the shorthand version because it wouldn't work with tags and having it as a drop-in replacement is more important.

Issue: grafana/jslib.k6.io#125

@allansson allansson requested a review from a team as a code owner August 13, 2024 09:09
@allansson allansson requested review from mstoykov, olegbespalov, inancgumus and ankur22 and removed request for a team August 13, 2024 09:09
Copy link
Member

@inancgumus inancgumus left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice 🎉

src/check.ts Outdated Show resolved Hide resolved
Copy link

@going-confetti going-confetti left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@allansson allansson merged commit f631eeb into master Aug 16, 2024
1 check passed
@allansson allansson deleted the feat/add-async-check-util branch August 16, 2024 09:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants