Skip to content

Best practice assertions for string inclusion and dynamic regex #381

Closed
@alubbe

Description

@alubbe

Today, I've run into two cases where I ended up writing helpers to get better errors. After writing them, I realized that it is somewhat against the spirit of "just writing assertions and getting readable errors". So I'd like to find out what you think is best practice here and whether it might make sense to expand what power-assert is displaying.

String inclusion

I've got some big dynamic string and want to make sure it contains another dynamic string. So I wrote

t.ok(bigString.includes(shortString))

When this fails, it will print the value of shortString and the return value of .includes(), which is false, but will not show me the value of bigString, which I need to properly debug it. So either I re-run the test with a console.log or I create helpers and refactor to

function includes(a,b){return a.includes(b)}
....
t.ok(includes(bigString, shortString))

In the case of a failure, this will print both bigString and shortString, allowing me to figure out what went wrong at the first glance.

Dynamic Regex

I've got a dynamic regex and want to run it against another dynamic string. So I wrote

t.ok(dynamicRegex.test(dynamicString))

Like in the above case, when this fails, it will print the value of dynamicString and the return value of .test(), which is false, but will not show me the value of dynamicRegex, which I need to properly debug it. I could use dynamicString.match(dynamicRegex), which will show the value of dynamicRegex, but it will also hide the value of dynamicString. So, like above, I wrote a helper

function test(a,b){return a.test(b)}
...
t.ok(test(dynamicRegex, dynamicString))

Conclusion

I'm guessing that power-assert avoids printing the top level object by default to avoid visual clutter, but in the case of strings and regex-objects (and probably numbers and booleans, as well), I would find it useful to print them.

This might end up being a power-assert issue, feel free to point that out and I will close & create an issue at its repo.

Metadata

Metadata

Assignees

No one assigned

    Labels

    blockedwaiting on something else to be resolved firstenhancementnew functionality

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions