This content originally appeared on Go Make Things and was authored by Go Make Things
On Friday, we looked at unit testing with vanilla JS. Today, we’re going to learn about some advanced matcher methods you can use.
You could build an entire suite of tests using just the expect.toBe()
matcher. But Jest includes a bunch of other matcher methods to make testing a bit easier.
For example, we’re currently testing that the name
variable works like this.
// should include the provided name
expect(sayHi('Merlin').includes('Merlin')).toBe(true);
We could instead use the toContain()
matcher method.
// should include the provided name
expect(sayHi('Merlin')).toContain('Merlin');
If we wanted to test that the string returned by sayHi()
without any options actually contained a value, we could use the toBeTruthy()
method.
// should have a value when no name is included
expect(sayHi()).toBeTruthy();
Jest also includes a not
property that will check that the matcher is not true
.
For example, what if instead of checking if the returned value was truthy, we wanted to make sure it’s length was not 0
? We could combine the not
property on the toHaveLength()
matcher.
// should have a value when no name is included
expect(sayHi()).not.toHaveLength(0);
Don’t feel like you have to memorize all of the matchers, or find the perfect one for the thing you’re trying to test.
If there’s a matcher that makes your life easier, use it. If not, toBe()
and the not
property work great!
And if you enjoyed this article and want to dig into additional JS testing topics like how to test DOM manipulation, how to test APIs, and how to test your entire app in a real browser, you might enjoy my course and ebook, Testing Vanilla JS.
Hot off the press! Explore new guides on Testing Vanilla JS and working with the command line, part of a new Tooling Bundle.
This content originally appeared on Go Make Things and was authored by Go Make Things
Go Make Things | Sciencx (2022-09-12T14:30:00+00:00) Diving deeper into unit testing vanilla JavaScript. Retrieved from https://www.scien.cx/2022/09/12/diving-deeper-into-unit-testing-vanilla-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.