I’m testing my GraphQL api using Jest.
I’m using a separate test suit for each query/mutation
I have 2 tests (each one in a separate test suit) where I mock one function (namely, Meteor’s callMethod
) that is used in mutations.
it('should throw error if email not found', async () => {
callMethod
.mockReturnValue(new Error('User not found [403]'))
.mockName('callMethod');
const query = FORGOT_PASSWORD_MUTATION;
const params = { email: 'user@example.com' };
const result = await simulateQuery({ query, params });
console.log(result);
// test logic
expect(callMethod).toBeCalledWith({}, 'forgotPassword', {
email: 'user@example.com',
});
// test resolvers
});
When I console.log(result)
I get
{ data: { forgotPassword: true } }
This behaviour is not what I want because in .mockReturnValue
I throw an Error and therefore expect result
to have an error object
Before this test, however, another is ran
it('should throw an error if wrong credentials were provided', async () => {
callMethod
.mockReturnValue(new Error('cannot login'))
.mockName('callMethod');
And it works fine, the error is thrown
I guess the problem is that mock doesn’t get reset after the test finishes.
In my jest.conf.js
I have clearMocks: true
Each test suit is in a separate file, and I mock functions before tests like this:
import simulateQuery from '../../../helpers/simulate-query';
import callMethod from '../../../../imports/api/users/functions/auth/helpers/call-accounts-method';
import LOGIN_WITH_PASSWORD_MUTATION from './mutations/login-with-password';
jest.mock(
'../../../../imports/api/users/functions/auth/helpers/call-accounts-method'
);
describe('loginWithPassword mutation', function() {
...
UPDATE
When I substituted .mockReturnValue
with .mockImplementation
everything worked out as expected:
callMethod.mockImplementation(() => {
throw new Error('User not found');
});
But that doesn’t explain why in another test .mockReturnValue
works fine…
NOTE:
I had this post in my personal blog but decided to try to link my RSS feed here and see how it goes.
Table of contents
- Assumptions
- Resources
- Scenario
Assumptions
- You know how to install and use Jest
- You know how to develop programs in JavaScript
Resources
- The Jest documentation.
Scenario
Currently, at work, there is an effort to refactor a codebase to make it more maintainable and scalable. The JavaScript code is running in an unusual environment that is not a browser nither a node server. I’m extracting common functionality into a utility library and writing unit-test for all functions.
I have used Jest before for frontend code but this is the first time using Jest for pure functions. Our use case is particular and we need to carefully choose which functions are going to throw/return an error.
When I start writing unit-test for a function that returns an error I started having issues with it. Let consider a sample function and let’s say that I’m going to throw an error if any of the parameters are null.
function addTwoNumbers(num1, num2) {
const num1IsNull = num1 === null
const num2IsNull = num2 === null
if (num1IsNull || num2IsNull) {
throw 'One of the parameters is not a number'
}
... // continue your code
}
// testing
const addTwoNumbers = require('path/to/addTwoNumbers')
describe('addTwoNumbers', () => {
it('should throw error if num1 is null', () => {
// This expect wont error out but it wont pass either.
expect(addTwoNumbers(null, 2)).toBe("One of the parameters is not a number")
})
})
Enter fullscreen mode
Exit fullscreen mode
The correct way to test this is not by expecting the string that comes back but rather that the function did throw
. Let’s consider the following test. It will be slightly different from the above.
const addTwoNumbers = require('path/to/addTwoNumbers')
describe('addTwoNumbers', () => {
it('should throw error if num1 is null', () => {
// Notice that expect takes a function that return the function under test.
// If I pass (3,5) the test will faild.
expect(() => addTwoNumbers(null, 2)).toThrow()
})
})
Enter fullscreen mode
Exit fullscreen mode
Let’s team up together 🤝
We’re hiring for a Senior Full Stack Engineer to join the DEV team. Want the deets? Head here to learn more about who we’re looking for.
In library or shared code, throwing errors can be useful to enforce an interface for a function for example.
This code should be tested, which can be challenging and differs based on the type of code under test.
This section tackles detection of throw
-ing a JavaScript error in a synchronous and an asynchronous context.
Check a synchronous function throws using the .toThrow
Jest matcher
Given a function that doesn’t throw like noError
as follows.
function noError() {
return 'success';
}
We can write a test asserting it doesn’t throw using expect().not.toThrow()
test('should not throw', () => {
expect(throws.bind(null)).not.toThrow(
new Error('throwing')
);
});
The test passes since the code under test doesn’t throw, but this time we get a Received function did not throw
error, which is maybe more descriptive and shows the advantage of using the Jest .toThrow
matcher.
npx jest src/04.01-no-throw.test.js
PASS src/04.01-no-throw.test.js
✓ should throw if passed true (3ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Say we have a function that throws:
function throws() {
throw new Error('throwing')
}
We can check that it throws with expect().toThrow(error)
.
test('should throw if passed true', () => {
expect(throws.bind(null)).toThrow(
new Error('throwing')
);
});
This test is passing since the function throws as we have asserted.
npx jest src/04.01-throws.test.js
PASS src/04.01-throws.test.js
✓ should throw if passed true (5ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Check an async function throws using expect().rejects.toEqual
The idiomatic Jest way to check an async
function throws is to use the await
or return
an expect(fn(param1)).rejects.toEqual(error)
.
Note: make sure to
await
orreturn
theexpect()
expression, otherwise Jest might not see the error as a failure but anUnHandledPromiseRejection
async function asyncThrowOrNot() {
throw new Error('async-throw')
}
test('should throw return expect()', async () => {
return expect(asyncThrowOrNot()).rejects.toEqual(
new Error('async-throw')
);
});
test('should throw await expect()', async () => {
await expect(asyncThrowOrNot()).rejects.toEqual(
new Error('async-throw')
);
});
These tests pass on async throw
‘s as expected, as per the following output.
npx jest src/04.01-async-throw.test.js
PASS src/04.01-async-throw.test.js
✓ should throw return expect() (3ms)
✓ should throw await expect() (1ms)
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
This section showed how one might test test that’s designed to throw, both in the synchronous and the asynchronous case.
The next section tackles mocking the output of stubbed sync and async functions with Jest.
Unit testing functions in JavaScript using Jest sometimes requires checking if an exception was thrown, or testing the specific type of exception thrown.
Suppose we want to test the following function using Node.js and assert that it indeed throws an error:
func.js:
const func = () => { throw new Error('my error') } module.exports = func
func.test.js:
const func = require('./func') describe('exception test', () => { it('should throw an error', () => { expect(func).toThrow() }) })
Note that func should not be called within the expect; calling the function will cause the error to be thrown unexpectedly.
We can also assert that an error is not thrown using:
expect(func).not.toThrow()
If we need to assert the specific name of the thrown error, we can use the following form:
it('should throw an error', () => { expect(func).toThrowError('my error') })
If no exceptions are thrown, Jest will report:
Expected the function to throw an error. But it didn't throw anything.
Expecting Async Functions to Throw Exceptions
Writing a unit test to expect an async function to throw an exception can be done as follows. First we define the async function in a module, then in the test code we use the rejects property to test for any thrown errors. Essentially, we are asserting that our function causes a promise rejection.
async-func.js:
const func = async () => { throw new Error('my error') } module.exports = func
async-func.test.js:
const func = require('./async-func.js') describe('exception test', () => { it('should throw an error', async () => { await expect(func()).rejects.toThrow() }) })
Note that the function passed to it() is async itself so that we can use await inside.
Note also that func is called inside expect in this case; this will cause a promise rejection which can then be tested within the rejects property.
The case of testing for a specific error to be thrown inside the async function is similar and looks like this:
it('should throw an error', async () => { await expect(func()).rejects.toThrowError('my error') })
Expect a Function with Parameters to Throw an Exception
If we want to expect a function to throw an exception for certain input parameters, the key point is that we must pass in a function definition and not call our function inside the expect. The code is below for an example of a function which should throw an exception for negative integer inputs:
func.js:
const func = (n) => { if (n < 0) { throw new Error("negative input") } return n } module.exports = func
func.spec.js:
const func = require('./func.js') describe('exception test', () => { it('should throw an exception', () => { expect( () => func(-1) // Do not simply call func ).toThrow() }) })
We pass an anonymous function to expect, which will throw for the input. Expect can then determine that this function will throw.
When you’re writing tests, you often need to check that values meet certain conditions. expect
gives you access to a number of «matchers» that let you validate different things.
Methods #
expect(value)
expect.extend(matchers)
this.isNot
this.utils
expect.anything()
expect.any(constructor)
expect.arrayContaining(array)
expect.assertions(number)
expect.stringContaining(string)
expect.stringMatching(regexp)
expect.objectContaining(object)
.not
.toBe(value)
.toHaveBeenCalled()
.toHaveBeenCalledTimes(number)
.toHaveBeenCalledWith(arg1, arg2, ...)
.toHaveBeenLastCalledWith(arg1, arg2, ...)
.toBeCloseTo(number, numDigits)
.toBeDefined()
.toBeFalsy()
.toBeGreaterThan(number)
.toBeGreaterThanOrEqual(number)
.toBeLessThan(number)
.toBeLessThanOrEqual(number)
.toBeInstanceOf(Class)
.toBeNull()
.toBeTruthy()
.toBeUndefined()
.toContain(item)
.toContainEqual(item)
.toEqual(value)
.toHaveLength(number)
.toMatch(regexpOrString)
.toMatchObject(object)
.toMatchSnapshot(optionalString)
.toThrow(error)
.toThrowErrorMatchingSnapshot()
Reference #
expect(value)
#
The expect
function is used every time you want to test a value. You will rarely call expect
by itself. Instead, you will use expect
along with a «matcher» function to assert something about a value.
It’s easier to understand this with an example. Let’s say you have a method bestLaCroixFlavor()
which is supposed to return the string 'grapefruit'
.
Here’s how you would test that:
test('the best flavor is grapefruit', () => { expect(bestLaCroixFlavor()).toBe('grapefruit'); });
In this case, toBe
is the matcher function. There are a lot of different matcher functions, documented below, to help you test different things.
The argument to expect
should be the value that your code produces, and any argument to the matcher should be the correct value. If you mix them up, your tests will still work, but the error messages on failing tests will look strange.
expect.extend(matchers)
#
You can use expect.extend
to add your own matchers to Jest. For example, let’s say that you’re testing a number theory library and you’re frequently asserting that numbers are divisible by other numbers. You could abstract that into a toBeDivisibleBy
matcher:
expect.extend({ toBeDivisibleBy(received, argument) { const pass = (received % argument == 0); if (pass) { return { pass: true, message: () => `expected ${received} not to be divisible by ${argument}`, } } else { return { pass: false, message: () => `expected ${received} to be divisible by ${argument}`, } } } }); test('even and odd numbers', () => { expect(100).toBeDivisibleBy(2); expect(101).not.toBeDivisibleBy(2); });
Matchers should return an object with two keys. pass
indicates whether there was a match or not, and message
provides a function with no arguments that returns an error message in case of failure. Thus, when pass
is false, message
should return the error message for when expect(x).yourMatcher()
fails. And when pass
is true, message
should return the error message for when expect(x).not.yourMatcher()
fails.
These helper functions can be found on this
inside a custom matcher:
this.isNot
#
A boolean to let you know this matcher was called with the negated .not
modifier allowing you to flip your assertion.
this.utils
#
There are a number of helpful tools exposed on this.utils
primarily consisting of the exports from jest-matcher-utils
.
The most useful ones are matcherHint
, printExpected
and printReceived
to format the error messages nicely. For example, take a look at the implementation for the toBe
matcher:
const diff = require('jest-diff'); expect.extend({ toBe(received, expected) { const pass = received === expected; const message = pass ? () => this.utils.matcherHint('.not.toBe') + 'nn' + `Expected value to not be (using ===):n` + ` ${this.utils.printExpected(expected)}n` + `Received:n` + ` ${this.utils.printReceived(received)}` : () => { const diffString = diff(expected, received, { expand: this.expand, }); return this.utils.matcherHint('.toBe') + 'nn' + `Expected value to be (using ===):n` + ` ${this.utils.printExpected(expected)}n` + `Received:n` + ` ${this.utils.printReceived(received)}` + (diffString ? `nnDifference:nn${diffString}` : ''); }; return {actual: received, message, pass}; }, });
This will print something like this:
expect(received).toBe(expected) Expected value to be (using ===): "banana" Received: "apple"
When an assertion fails, the error message should give as much signal as necessary to the user so they can resolve their issue quickly. You should craft a precise failure message to make sure users of your custom assertions have a good developer experience.
expect.anything()
#
expect.anything()
matches anything but null
or undefined
. You can use it inside toEqual
or toBeCalledWith
instead of a literal value. For example, if you want to check that a mock function is called with a non-null argument:
test('map calls its argument with a non-null argument', () => { let mock = jest.fn(); [1].map(mock); expect(mock).toBeCalledWith(expect.anything()); })
expect.any(constructor)
#
expect.any(constructor)
matches anything that was created with the given constructor. You can use it inside toEqual
or toBeCalledWith
instead of a literal value. For example, if you want to check that a mock function is called with a number:
function randocall(fn) { return fn(Math.floor(Math.random() * 6 + 1)); } test('randocall calls its callback with a number', () => { let mock = jest.fn(); randocall(mock); expect(mock).toBeCalledWith(expect.any(Number)); })
expect.arrayContaining(array)
#
expect.arrayContaining(array)
matches any array made up entirely of elements in the provided array. You can use it inside toEqual
or toBeCalledWith
instead of a literal value. For example, this code checks that rollDice
returns only valid numbers:
function rollDice(n) { let answer = []; for (let i = 0; i < n; i++) { answer.push(Math.floor(Math.random() * 6 + 1)); } return answer; } test('rollDice only returns valid numbers', () => { expect(rollDice(100)).toEqual(expect.arrayContaining([1, 2, 3, 4, 5, 6])); })
expect.assertions(number)
#
expect.assertions(number)
verifies that a certain number of assertions are called during a test. This is often useful when testing asynchronous code, in order to make sure that assertions in a callback actually got called.
For example, let’s say that we have a few functions that all deal with state. prepareState
calls a callback with a state object, validateState
runs on that state object, and waitOnState
returns a promise that waits until all prepareState
callbacks complete. We can test this with:
test('prepareState prepares a valid state', () => { expect.assertions(1); prepareState((state) => { expect(validateState(state)).toBeTruthy(); }) return waitOnState(); })
The expect.assertions(1)
call ensures that the prepareState
callback actually gets called.
expect.stringContaining(string)
#
expect.stringContaining(string)
matches any string that contains the exact provided string.
expect.stringMatching(regexp)
#
expect.stringMatching(regexp)
matches any string that matches the provided regexp. You can use it inside toEqual
or toBeCalledWith
instead of a literal value. For example, let’s say you want to test that randomCoolNames()
only returns names that are cool:
function randomCoolName() { let lastName = ( 'TRFGBNMPLZ'[Math.floor(Math.random() * 10)] + 'aeiou'[Math.floor(Math.random() * 5)] + 'mnbvxdstrp'[Math.floor(Math.random() * 10)]); return 'Kevin ' + lastName; } function randomCoolNames() { let answer = []; for (let i = 0; i < 100; i++) { answer.push(randomCoolName()); } return answer; } test('randomCoolNames only returns cool names', () => { let coolRegex = /^Kevin/; expect(randomCoolNames).toEqual( expect.arrayContaining(expect.stringMatching(coolRegex))); });
This example also shows how you can nest multiple asymmetric matchers, with expect.stringMatching
inside the expect.arrayContaining
.
expect.objectContaining(object)
#
expect.objectContaining(object)
matches any object that recursively matches the provided keys. This is often handy in conjunction with other asymmetric matchers.
For example, let’s say that we expect an onPress
function to be called with an Event
object, and all we need to verify is that the event has event.x
and event.y
properties. We can do that with:
test('onPress gets called with the right thing', () => { let onPress = jest.fn(); simulatePresses(onPress); expect(onPress).toBeCalledWith(expect.objectContaining({ x: expect.any(Number), y: expect.any(Number), })); })
.not
#
If you know how to test something, .not
lets you test its opposite. For example, this code tests that the best La Croix flavor is not coconut:
test('the best flavor is not coconut', () => { expect(bestLaCroixFlavor()).not.toBe('coconut'); });
.toBe(value)
#
toBe
just checks that a value is what you expect. It uses ===
to check
strict equality.
For example, this code will validate some properties of the beverage
object:
const can = { ounces: 12, name: 'pamplemousse', }; describe('the can', () => { test('has 12 ounces', () => { expect(can.ounces).toBe(12); }); test('has a sophisticated name', () => { expect(can.name).toBe('pamplemousse'); }); });
Don’t use toBe
with floating-point numbers. For example, due to rounding, in JavaScript 0.2 + 0.1
is not strictly equal to 0.3
. If you have floating point numbers, try .toBeCloseTo
instead.
.toHaveBeenCalled()
#
Also under the alias: .toBeCalled()
Use .toHaveBeenCalled
to ensure that a mock function got called.
For example, let’s say you have a drinkAll(drink, flavor)
function that takes a drink
function and applies it to all available beverages. You might want to check that drink
gets called for 'lemon'
, but not for 'octopus'
, because 'octopus'
flavor is really weird and why would anything be octopus-flavored? You can do that with this test suite:
describe('drinkAll', () => { test('drinks something lemon-flavored', () => { let drink = jest.fn(); drinkAll(drink, 'lemon'); expect(drink).toHaveBeenCalled(); }); test('does not drink something octopus-flavored', () => { let drink = jest.fn(); drinkAll(drink, 'octopus'); expect(drink).not.toHaveBeenCalled(); }); });
.toHaveBeenCalledTimes(number)
#
Use .toHaveBeenCalledTimes
to ensure that a mock function got called exact number of times.
For example, let’s say you have a drinkEach(drink, Array<flavor>)
function that takes a drink
function and applies it to array of passed beverages. You might want to check that drink function was called exact number of times. You can do that with this test suite:
test('drinkEach drinks each drink', () => { let drink = jest.fn(); drinkEach(drink, ['lemon', 'octopus']); expect(drink).toHaveBeenCalledTimes(2); });
.toHaveBeenCalledWith(arg1, arg2, ...)
#
Also under the alias: .toBeCalledWith
Use .toHaveBeenCalledWith
to ensure that a mock function was called with specific arguments.
For example, let’s say that you can register a beverage with a register
function, and applyToAll(f)
should apply the function f
to all registered beverages. To make sure this works, you could write:
test('registration applies correctly to orange La Croix', () => { let beverage = new LaCroix('orange'); register(beverage); let f = jest.fn(); applyToAll(f); expect(f).toHaveBeenCalledWith(beverage); });
.toHaveBeenLastCalledWith(arg1, arg2, ...)
#
Also under the alias: .lastCalledWith(arg1, arg2, ...)
If you have a mock function, you can use .toHaveBeenLastCalledWith
to test what arguments it was last called with. For example, let’s say you have a applyToAllFlavors(f)
function that applies f
to a bunch of flavors, and you want to ensure that when you call it, the last flavor it operates on is 'mango'
. You can write:
test('applying to all flavors does mango last', () => { let drink = jest.fn(); applyToAllFlavors(drink); expect(drink).toHaveBeenLastCalledWith('mango'); });
.toBeCloseTo(number, numDigits)
#
Using exact equality with floating point numbers is a bad idea. Rounding means that intuitive things fail. For example, this test fails:
test('adding works sanely with simple decimals', () => { expect(0.2 + 0.1).toBe(0.3); });
It fails because in JavaScript, 0.2 + 0.1
is actually 0.30000000000000004
. Sorry.
Instead, use .toBeCloseTo
. Use numDigits
to control how many digits after the decimal point to check. For example, if you want to be sure that 0.2 + 0.1
is equal to 0.3
with a precision of 5 decimal digits, you can use this test:
test('adding works sanely with simple decimals', () => { expect(0.2 + 0.1).toBeCloseTo(0.3, 5); });
The default for numDigits
is 2, which has proved to be a good default in most cases.
.toBeDefined()
#
Use .toBeDefined
to check that a variable is not undefined. For example, if you just want to check that a function fetchNewFlavorIdea()
returns something, you can write:
test('there is a new flavor idea', () => { expect(fetchNewFlavorIdea()).toBeDefined(); });
You could write expect(fetchNewFlavorIdea()).not.toBe(undefined)
, but it’s better practice to avoid referring to undefined
directly in your code.
.toBeFalsy()
#
Use .toBeFalsy
when you don’t care what a value is, you just want to ensure a value is false in a boolean context. For example, let’s say you have some application code that looks like:
drinkSomeLaCroix(); if (!getErrors()) { drinkMoreLaCroix(); }
You may not care what getErrors
returns, specifically — it might return false
, null
, or 0
, and your code would still work. So if you want to test there are no errors after drinking some La Croix, you could write:
test('drinking La Croix does not lead to errors', () => { drinkSomeLaCroix(); expect(getErrors()).toBeFalsy(); });
In JavaScript, there are six falsy values: false
, 0
, ''
, null
, undefined
, and NaN
. Everything else is truthy.
.toBeGreaterThan(number)
#
To compare floating point numbers, you can use toBeGreaterThan
. For example, if you want to test that ouncesPerCan()
returns a value of more than 10 ounces, write:
test('ounces per can is more than 10', () => { expect(ouncesPerCan()).toBeGreaterThan(10); });
.toBeGreaterThanOrEqual(number)
#
To compare floating point numbers, you can use toBeGreaterThanOrEqual
. For example, if you want to test that ouncesPerCan()
returns a value of at least 12 ounces, write:
test('ounces per can is at least 12', () => { expect(ouncesPerCan()).toBeGreaterThanOrEqual(12); });
.toBeLessThan(number)
#
To compare floating point numbers, you can use toBeLessThan
. For example, if you want to test that ouncesPerCan()
returns a value of less than 20 ounces, write:
test('ounces per can is less than 20', () => { expect(ouncesPerCan()).toBeLessThan(20); });
.toBeLessThanOrEqual(number)
#
To compare floating point numbers, you can use toBeLessThanOrEqual
. For example, if you want to test that ouncesPerCan()
returns a value of at most 12 ounces, write:
test('ounces per can is at most 12', () => { expect(ouncesPerCan()).toBeLessThanOrEqual(12); });
.toBeInstanceOf(Class)
#
Use .toBeInstanceOf(Class)
to check that an object is an instance of a class. This matcher uses instanceof
underneath.
class A {} expect(new A()).toBeInstanceOf(A); expect(() => {}).toBeInstanceOf(Function); expect(new A()).toBeInstanceOf(Function);
.toBeNull()
#
.toBeNull()
is the same as .toBe(null)
but the error messages are a bit nicer. So use .toBeNull()
when you want to check that something is null.
function bloop() { return null; } test('bloop returns null', () => { expect(bloop()).toBeNull(); });
.toBeTruthy()
#
Use .toBeTruthy
when you don’t care what a value is, you just want to ensure a value is true in a boolean context. For example, let’s say you have some application code that looks like:
drinkSomeLaCroix(); if (thirstInfo()) { drinkMoreLaCroix(); }
You may not care what thirstInfo
returns, specifically — it might return true
or a complex object, and your code would still work. So if you just want to test that thirstInfo
will be truthy after drinking some La Croix, you could write:
test('drinking La Croix leads to having thirst info', () => { drinkSomeLaCroix(); expect(thirstInfo()).toBeTruthy(); });
In JavaScript, there are six falsy values: false
, 0
, ''
, null
, undefined
, and NaN
. Everything else is truthy.
.toBeUndefined()
#
Use .toBeUndefined
to check that a variable is undefined. For example, if you want to check that a function bestDrinkForFlavor(flavor)
returns undefined
for the 'octopus'
flavor, because there is no good octopus-flavored drink:
test('the best drink for octopus flavor is undefined', () => { expect(bestDrinkForFlavor('octopus')).toBeUndefined(); });
You could write expect(bestDrinkForFlavor('octopus')).toBe(undefined)
, but it’s better practice to avoid referring to undefined
directly in your code.
.toContain(item)
#
Use .toContain
when you want to check that an item is in a list. For testing the items in the list, this uses ===
, a strict equality check.
For example, if getAllFlavors()
returns a list of flavors and you want to be sure that lime
is in there, you can write:
test('the flavor list contains lime', () => { expect(getAllFlavors()).toContain('lime'); });
.toContainEqual(item)
#
Use .toContainEqual
when you want to check that an item is in a list.
For testing the items in the list, this matcher recursively checks the equality of all fields, rather than checking for object identity.
describe('my beverage', () => { test('is delicious and not sour', () => { const myBeverage = {delicious: true, sour: false}; expect(myBeverages()).toContainEqual(myBeverage); }); });
.toEqual(value)
#
Use .toEqual
when you want to check that two objects have the same value. This matcher recursively checks the equality of all fields, rather than checking for object identity. For example, toEqual
and toBe
behave differently in this test suite, so all the tests pass:
const can1 = { flavor: 'grapefruit', ounces: 12, }; const can2 = { flavor: 'grapefruit', ounces: 12, }; describe('the La Croix cans on my desk', () => { test('have all the same properties', () => { expect(can1).toEqual(can2); }); test('are not the exact same can', () => { expect(can1).not.toBe(can2); }); });
.toHaveLength(number)
#
Use .toHaveLength
to check that an object has a .length
property and it is set to a certain numeric value.
This is especially useful for checking arrays or strings size.
expect([1, 2, 3]).toHaveLength(3); expect('abc').toHaveLength(3); expect('').not.toHaveLength(5);
.toMatch(regexpOrString)
#
Use .toMatch
to check that a string matches a regular expression.
For example, you might not know what exactly essayOnTheBestFlavor()
returns, but you know it’s a really long string, and the substring grapefruit
should be in there somewhere. You can test this with:
describe('an essay on the best flavor', () => { test('mentions grapefruit', () => { expect(essayOnTheBestFlavor()).toMatch(/grapefruit/); expect(essayOnTheBestFlavor()).toMatch(new RegExp('grapefruit')); }) })
This matcher also accepts a string, which it will try to match:
describe('grapefruits are healthy', () => { test('grapefruits are a fruit', () => { expect('grapefruits').toMatch('fruit'); }) })
.toMatchObject(object)
#
Use .toMatchObject
to check that a JavaScript object matches a subset of the properties of an object.
const houseForSale = { bath: true, kitchen: { amenities: ['oven', 'stove', 'washer'], area: 20, wallColor: 'white' }, bedrooms: 4 }; const desiredHouse = { bath: true, kitchen: { amenities: ['oven', 'stove', 'washer'], wallColor: 'white' } }; test('the house has my desired features', () => { expect(houseForSale).toMatchObject(desiredHouse); });
.toMatchSnapshot(optionalString)
#
This ensures that a value matches the most recent snapshot. Check out the Snapshot Testing guide for more information.
You can also specify an optional snapshot name. Otherwise, the name is inferred from the test.
Note: While snapshot testing is most commonly used with React components, any serializable value can be used as a snapshot.
.toThrow(error)
#
Also under the alias: .toThrowError(error)
Use .toThrow
to test that a function throws when it is called. For example, if we want to test that drinkFlavor('octopus')
throws, because octopus flavor is too disgusting to drink, we could write:
test('throws on octopus', () => { expect(() => { drinkFlavor('octopus'); }).toThrow(); });
If you want to test that a specific error gets thrown, you can provide an argument to toThrow
. The argument can be a string for the error message, a class for the error, or a regex that should match the error. For example, let’s say that drinkFlavor
is coded like this:
function drinkFlavor(flavor) { if (flavor == 'octopus') { throw new DisgustingFlavorError('yuck, octopus flavor'); } }
We could test this error gets thrown in several ways:
test('throws on octopus', () => { function drinkOctopus() { drinkFlavor('octopus'); } expect(drinkOctopus).toThrowError('yuck, octopus flavor'); expect(drinkOctopus).toThrowError(/yuck/); expect(drinkOctopus).toThrowError(DisgustingFlavorError); });
.toThrowErrorMatchingSnapshot()
#
Use .toThrowErrorMatchingSnapshot
to test that a function throws a error matching the most recent snapshot when it is called. For example, let’s say you have a drinkFlavor
function that throws whenever the flavor is 'octopus'
, and is coded like this:
function drinkFlavor(flavor) { if (flavor == 'octopus') { throw new DisgustingFlavorError('yuck, octopus flavor'); } }
The test for this function will look this way:
test('throws on octopus', () => { function drinkOctopus() { drinkFlavor('octopus'); } expect(drinkOctopus).toThrowErrorMatchingSnapshot(); });
And it will generate the following snapshot:
exports[`drinking flavors throws on octopus 1`] = `"yuck, octopus flavor"`;
Check out React Tree Snapshot Testing for more information on snapshot testing.
Whenever you are looking to test an error thrown by a function in Jest, you want to pass the function to the expect
, rather than invoking the function. Take a look at the following examples:
const functionWithError = param => {
throw new Error()
}
it('should throw an error', () => {
expect(functionWithError).toThrow(Error)
})
Copied to clipboard!
We have a mock function and we want to test whether it throws the error we are expecting. We can do this by simply passing the function to the expect without actually invoking it, and calling the toThrow
method on it with the passed error.
But what if you have to call the function, for example, to provide parameters? In this case, you can wrap the function into an anonymous function:
// 🟢 Do
expect(() => functionWithError()).toThrow(Error)
// 🔴 Don’t
expect(functionWithError()).toThrow(Error)
expect(functionWithError('param')).toThrow(Error)
Copied to clipboard!
Notice that if you try to call the function directly inside the expect
, it will fail the test as the error is not caught and the assertion will fail. You can also test other types of errors by passing the correct error to toThrow
:
expect(functionWithError()).toThrow(EvalError)
expect(functionWithError()).toThrow(RangeError)
expect(functionWithError()).toThrow(ReferenceError)
expect(functionWithError()).toThrow(SyntaxError)
expect(functionWithError()).toThrow(TypeError)
expect(functionWithError()).toThrow(URIError)
expect(functionWithError()).toThrow(AggregateError)
Pass the correct type of error to test different types
Copied to clipboard!
Lastly, if you would like to test the error message itself, toThrow
also accepts a string so you can test both the type and message:
const functionWithError = () => {
throw new TypeError('Custom Error')
}
it('should throw an error', () => {
expect(functionWithError).toThrow(TypeError)
expect(functionWithError).toThrow('Custom Error')
})
Copied to clipboard!
How to Mock process.env in Jest
Unit testing environment-specific parts in your application
Learn how you can properly mock environment variables in your Jest tests to correctly test environment-specific parts in your application.
Время прочтения
7 мин
Просмотры 60K
Здравствуй, Хабр! Данное руководство является первой частью в запланированном цикле статей про такой замечательный фреймворк для тестирования как Jest. Материал будет полезен новичкам и тем, кто только знакомится с тестированием, и хотел бы изучить этот фреймворк. В первой части мы разберём: как начать работу с jest, как написать простой тест, и какие есть методы для сопоставления проверяемых значение с ожидаемыми. Кому интересно — добро пожаловать под кат!
Что такое Jest?
Как указано на домашней странице проекта:
Jest — это восхитительная среда тестирования JavaScript с упором на простоту.
И действительно, Jest очень простой. Он не требует дополнительных настроек, легкий в понимании и применении, а так же имеет довольно хорошую документацию. Отлично подходит для проектов использующих Node, React, Angular, Vue, Babel, TypeScript и не только.
Также он имеет открытый исходный код и поддерживается компанией Facebook.
Установка
Для установки Jest в ваш проект выполните:
npm install --save-dev jest
Если вы используете yarn:
yarn add --dev jest
После установки можете обновить секцию scripts вашего package.json:
“scripts” : {
“test”: “jest”
}
С помощью такого простого вызова мы уже можем запустить наши тесты (на самом деле jest потребует существование хотя бы одного теста).
Также можно установить глобально (но так делать я бы не рекомендовал, так как по мне глобальная установка модулей является плохой практикой):
npm install jest --global
И соответственно для yarn:
yarn global add jest
После этого вы можете использовать jest непосредственно из командной строки.
При помощи вызова команды jest —init в корне проекта, ответив на несколько вопросов, вы получите файл с настройками jest.config.js. Или можно добавить конфигурацию прямиком в ваш package.json. Для этого добавьте в корень json ключ «jest» и в соответствующем ему объекте можете добавлять необходимые вам настройки. Сами опции мы разберем позже. На данном этапе в этом нет необходимости, поскольку jest можно использовать «сходу», без дополнительных конфигураций.
Первый тест
Давайте создадим файл first.test.js и напишем наш первый тест:
//first.test.js
test('My first test', () => {
expect(Math.max(1, 5, 10)).toBe(10);
});
И запустим наши тесты с помощью npm run test или непосредственно командой jest (если он установлен глобально). После запуска мы увидим отчет о прохождении тестов.
<b>PASS</b> ./first.test.js
✓ My first test (1 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.618 s, estimated 1 s
Давайте «сломаем» наш тест и запустим jest повторно:
//first.test.js
test('My first test', () => {
expect(Math.max(1, 5, 10)).toBe(5);
});
Как мы видим, теперь наш тест не проходит проверки. Jest отображает подробную информацию о том, где возникла проблема, какой был ожидаемый результат, и что мы получили вместо него.
Теперь давайте разберём код самого теста. Функция test используется для создания нового теста. Она принимает три аргумента (в примере мы использовали вызов с двумя аргументами). Первый — строка с названием теста, его jest отобразит в отчете. Второй — функция, которая содержит логику нашего теста. Также можно использовать 3-й аргумент — таймаут. Он является не обязательным, а его значение по умолчанию составляет 5 секунд. Задаётся в миллисекундах. Этот параметр необходим когда мы работаем с асинхронным кодом и возвращаем из функции теста промис. Он указывает как долго jest должен ждать разрешения промиса. По истечению этого времени, если промис не был разрешен — jest будет считать тест не пройденным. Подробнее про работу с асинхронными вызовами будет в следующих частях. Также вместо test() можно использовать it(). Разницы между такими вызовами нету. it() это просто алиас на функцию test().
Внутри функции теста мы сначала вызываем expect(). Ему мы передаем значение, которое хотим проверить. В нашем случае, это результат вызова Math.max(1, 5, 10). expect() возвращает объект «обертку», у которой есть ряд методов для сопоставления полученного значения с ожидаемым. Один из таких методов мы и использовали — toBe.
Давайте разберем основные из этих методов:
- toBe() — подходит, если нам надо сравнивать примитивные значения или является ли переданное значение ссылкой на тот же объект, что указан как ожидаемое значение. Сравниваются значения при помощи Object.is(). В отличие от === это дает возможность отличать 0 от -0, проверить равенство NaN c NaN.
- toEqual() — подойдёт, если нам необходимо сравнить структуру более сложных типов. Он сравнит все поля переданного объекта с ожидаемым. Проверит каждый элемент массива. И сделает это рекурсивно по всей вложенности.
test('toEqual with objects', () => { expect({ foo: 'foo', subObject: { baz: 'baz' } }) .toEqual({ foo: 'foo', subObject: { baz: 'baz' } }); // Ок expect({ foo: 'foo', subObject: { num: 0 } }) .toEqual({ foo: 'foo', subObject: { baz: 'baz' } }); // А вот так ошибка. }); test('toEqual with arrays', () => { expect([11, 19, 5]).toEqual([11, 19, 5]); // Ок expect([11, 19, 5]).toEqual([11, 19]); // Ошибка });
- toContain() — проверят содержит массив или итерируемый объект значение. Для сравнения используется оператор ===.
const arr = ['apple', 'orange', 'banana']; expect(arr).toContain('banana'); expect(new Set(arr)).toContain('banana'); expect('apple, orange, banana').toContain('banana');
- toContainEqual() — проверяет или содержит массив элемент с ожидаемой структурой.
expect([{a: 1}, {b: 2}]).toContainEqual({a: 1});
- toHaveLength() — проверяет или свойство length у объекта соответствует ожидаемому.
expect([1, 2, 3, 4]).toHaveLength(4); expect('foo').toHaveLength(3); expect({ length: 1 }).toHaveLength(1);
- toBeNull() — проверяет на равенство с null.
- toBeUndefined() — проверяет на равенство с undefined.
- toBeDefined() — противоположность toBeUndefined. Проверяет или значение !== undefined.
- toBeTruthy() — проверяет или в булевом контексте значение соответствует true. Тоесть любые значения кроме false, null, undefined, 0, NaN и пустых строк.
- toBeFalsy() — противоположность toBeTruthy(). Проверяет или в булевом контексте значение соответствует false.
- toBeGreaterThan() и toBeGreaterThanOrEqual() — первый метод проверяет или переданное числовое значение больше, чем ожидаемое >, второй проверяет больше или равно ожидаемому >=.
- toBeLessThan() и toBeLessThanOrEqual() — противоположность toBeGreaterThan() и toBeGreaterThanOrEqual()
- toBeCloseTo() — удобно использовать для чисел с плавающей запятой, когда вам не важна точность и вы не хотите, чтобы тест зависел от незначительной разницы в дроби. Вторым аргументом можно передать до какого знака после запятой необходима точность при сравнении.
const num = 0.1 + 0.2; // 0.30000000000000004 expect(num).toBeCloseTo(0.3); expect(Math.PI).toBeCloseTo(3.14, 2);
- toMatch() — проверяет соответствие строки регулярному выражению.
expect('Banana').toMatch(/Ba/);
- toThrow() — используется в случаях, когда надо проверить исключение. Можно проверить как сам факт ошибки, так и проверить на выброс исключения определенного класса, либо по сообщению ошибки, либо по соответствию сообщения регулярному выражению.
function funcWithError() { throw new Error('some error'); } expect(funcWithError).toThrow(); expect(funcWithError).toThrow(Error); expect(funcWithError).toThrow('some error'); expect(funcWithError).toThrow(/some/);
- not — это свойство позволяет сделать проверки на НЕравенство. Оно предоставляет объект, который имеет все методы перечисленные выше, но работать они будут наоборот.
expect(true).not.toBe(false); expect({ foo: 'bar' }).not.toEqual({}); function funcWithoutError() {} expect(funcWithoutError).not.toThrow();
Давайте напишем пару простых тестов. Для начала создадим простой модуль, который будет содержать несколько методов для работы с окружностями.
// src/circle.js
const area = (radius) => Math.PI * radius ** 2;
const circumference = (radius) => 2 * Math.PI * radius;
module.exports = { area, circumference };
Далее добавим тесты:
// tests/circle.test.js
const circle = require('../src/circle');
test('Circle area', () => {
expect(circle.area(5)).toBeCloseTo(78.54);
expect(circle.area()).toBeNaN();
});
test('Circumference', () => {
expect(circle.circumference(11)).toBeCloseTo(69.1, 1);
expect(circle.circumference()).toBeNaN();
});
В этих тестах мы проверили результат работы 2-х методов — area и circumference. При помощи метода toBeCloseTo мы сверились с ожидаемым результатом. В первом случае мы проверили или вычисляемая площадь круга с радиусом 5 приблизительно равна 78.54, при этом разница с полученым значением (оно составит 78.53981633974483) не большая и тест будет засчитан. Во втором мы указали, что нас интересует проверка с точностью до 1 знака после запятой. Также мы вызвали наши методы без аргументов и проверили результат с помощью toBeNaN. Поскольку результат их выполнения будет NaN, то и тесты будут пройдены успешно.
Разберём ещё один пример. Создадим функцию, которая будет фильтровать массив продуктов по цене:
// src/productFilter.js
const byPriceRange = (products, min, max) =>
products.filter(item => item.price >= min && item.price <= max);
module.exports = { byPriceRange };
И добавим тест:
// tests/product.test.js
const productFilter = require('../src/producFilter');
const products = [
{ name: 'onion', price: 12 },
{ name: 'tomato', price: 26 },
{ name: 'banana', price: 29 },
{ name: 'orange', price: 38 }
];
test('Test product filter by range', () => {
const FROM = 15;
const TO = 30;
const filteredProducts = productFilter.byPriceRange(products, FROM, TO);
expect(filteredProducts).toHaveLength(2);
expect(filteredProducts).toContainEqual({ name: 'tomato', price: 26 });
expect(filteredProducts).toEqual([{ name: 'tomato', price: 26 }, { name: 'banana', price: 29 }]);
expect(filteredProducts[0].price).toBeGreaterThanOrEqual(FROM);
expect(filteredProducts[1].price).toBeLessThanOrEqual(TO);
expect(filteredProducts).not.toContainEqual({ name: 'orange', price: 38 });
});
В этом тесте мы проверям результат работы функии byRangePrice. Сначала мы проверили соответствие длины полученого массива ожидаемой — 2. Следующая проверка требует, чтобы в массиве находился элемент — { name: ‘tomato’, price: 26 }. Объект в массиве и объект переданный toContainEqual — это два разных объекта, а не ссылка на один и тот же. Но toContainEqual сверит каждое свойство. Так как оба объекта идентичные — проверка пройдет успешно. Далее мы используем toEqual для провеки структуры всего массива и его элементов. Методы toBeGreaterThanOrEqual и toBeLessThanOrEqual помогут нам проверить price первого и второго элемента массива. И, наконец, вызов not.toContainEqual сделает проверку, не содержится ли в массиве элемент — { name: ‘orange’, price: 38 }, которого по условию там быть не должно.
В данных примерах мы написали несколько простых тестов используя функции проверки описанные выше. В следующих частях мы разберём работу с асинхронным кодом, функции jest которые не затрагивались в этой части туториала, поговорим о его настройке и многое другое.
The code
Let’s consider a simple function that checks for equality of two passwords, and it throws an error when the first one is not provided:
export default function samePasswordsValidator(password, otherPassword) {
if (!password) {
throw new Error("no password given");
}
return password === otherPassword;
}
Try-catch idiom (bad)
When testing the code that throws exceptions, one immediately comes up with the idea of using the try-catch
idiom in the test code:
it('throws an error when first argument is `null`', () => {
try {
samePasswordsValidator(null, "bar");
} catch (error) {
expect(error.message).toBe("no password given");
}
});
Generally speaking, this is not the best approach. The test passes when the first argument is null
as expected. But when the code is about to change and the exception won’t be thrown anymore the test still passes. So, the code change won’t be detected by the test.
Try-catch idiom (better)
To overcome that issue, one could expect that actual assertion will be executed and fail the test if it does not happen. This can be done pretty easily with expect.assertions
which verifies that a certain number of assertions are called during a test:
it('throws an error when first argument is `null`', () => {
expect.assertions(1);
try {
samePasswordsValidator(null, "bar");
} catch (error) {
expect(error.message).toBe("no password given");
}
});
Now, when no exception is thrown, the test fails:
Error: expect.assertions(1)
Expected one assertion to be called but received zero assertion calls.
toThrow
assertions (best)
To make the code even more expressive a built-in toThrow
matcher can be used:
it('throws an error when first argument is `null`', () => {
expect(() => samePasswordsValidator(null, "bar")).toThrow("no password given");
});
And again, when no exception is thrown, Jest informs us clearly about it with a failed test:
Error: expect(received).toThrow(expected)
Expected substring: "no password given"
Received function did not throw
Note that toThrow
matcher can be used to not only check the error message, but also the exact type of the error:
it('throws an error when first argument is `null`', () => {
expect(() => samePasswordsValidator(null, "bar")).toThrow(Error);
expect(() => samePasswordsValidator(null, "bar")).toThrow(new Error("no password given"));
});
See also
- Testing promise rejection in JavaScript with Jest
- Jest Vanilla JS Starter
- Different ways of handling exceptions in JUnit. Which one to choose?