links: GitHub - Chai plugin
Sinon.JS property/method | Sinon–Chai assertion |
---|---|
called | spy.should.have.been.called |
callCount | spy.should.have.callCount(n) |
calledOnce | spy.should.have.been.calledOnce |
calledTwice | spy.should.have.been.calledTwice |
calledThrice | spy.should.have.been.calledThrice |
calledBefore | spy1.should.have.been.calledBefore(spy2) |
calledAfter | spy1.should.have.been.calledAfter(spy2) |
calledWithNew | spy.should.have.been.calledWithNew |
alwaysCalledWithNew | spy.should.always.have.been.calledWithNew |
calledOn | spy.should.have.been.calledOn(context) |
alwaysCalledOn | spy.should.always.have.been.calledOn(context) |
calledWith | spy.should.have.been.calledWith(...args) |
alwaysCalledWith | spy.should.always.have.been.calledWith(...args) |
calledWithExactly | spy.should.have.been.calledWithExactly(...args) |
alwaysCalledWithExactly | spy.should.always.have.been.calledWithExactly(...args) |
calledWithMatch | spy.should.have.been.calledWithMatch(...args) |
alwaysCalledWithMatch | spy.should.always.have.been.calledWithMatch(...args) |
returned | spy.should.have.returned(returnVal) |
alwaysReturned | spy.should.have.always.returned(returnVal) |
threw | spy.should.have.thrown(errorObjOrErrorTypeStringOrNothing) |
alwaysThrew | spy.should.have.always.thrown(errorObjOrErrorTypeStringOrNothing) |
links: docs
Chains:
- to
- be * been * is * that * which * and * has * have * with * at * of * same
Assertions | Description |
---|---|
.a(type) |
@param{ String }type The a and an assertions are aliases that can be used either as language chains or to assert a value's type.
// typeof
// language chain
|
.above(value) |
@param{ Number }value Asserts that the target is greater than value.
Can also be used in conjunction with length to assert a minimum length. The benefit being a more informative error message than if the length was supplied directly.
|
.all | Sets the all flag (opposite of the any flag) later used by the keys assertion.
|
.any | Sets the any flag, (opposite of the all flag) later used in the keys assertion.
|
.arguments | Asserts that the target is an arguments object.
function test () { expect(arguments).to.be.arguments; } |
.below(value) |
@param{ Number }value Asserts that the target is less than value.
Can also be used in conjunction with length to assert a maximum length. The benefit being a more informative error message than if the length was supplied directly.
|
.change(function) |
@param{ String }object
Asserts that a function changes an object property
|
.closeTo(expected, delta) |
@param{ Number }expected Asserts that the target is equal expected, to within a +/- delta range.
|
.decrease(function) |
@param{ String }object Asserts that a function decreases an object property var obj = { val: 10 };
|
.deep | Sets the deep flag, later used by the equal and property assertions.
|
.empty | Asserts that the target's length is 0. For arrays, it checks the length property. For objects, it gets the count of enumerable keys.
|
.eql(value) |
@param{ Mixed }value Asserts that the target is deeply equal to value.
|
.equal(value) |
@param{ Mixed }value Asserts that the target is strictly equal (===) to value. Alternately, if the deep flag is set, asserts that the target is deeply equal to value.
|
.exist |
Asserts that the target is neither null nor undefined.
var foo = 'hi', bar = null, baz;
|
.false |
Asserts that the target is false.
|
.include(value) |
@param{ Object | String | Number }obj The include and contain assertions can be used as either property based language chains or as methods to assert the inclusion of an object in an array or a substring in a string. When used as language chains, they toggle the contains flag for the keys assertion.
|
.increase(function) |
@param{ String }object Asserts that a function increases an object property var obj = { val: 10 };
|
.instanceof(constructor) |
@param{ Constructor }constructor Asserts that the target is an instance of constructor. var Tea = function (name) { this.name = name; }
|
.itself | Sets the itself flag, later used by the respondTo assertion.
function Foo() {} Foo.bar = function() {} Foo.prototype.baz = function() {}
|
.keys(key1, [key2], [...]) |
@param{ String... | Array | Object }keys
Asserts that the target contains any or all of the passed-in keys. Use in combination with any, all, contains, or have will affect what will pass.
|
.least(value) |
@param{ Number }value Asserts that the target is greater than or equal to value.
|
.lengthOf(value) |
@param{ Number }length
Can also be used as a chain precursor to a value comparison for the length property.
|
.match(regexp) |
@param{ RegExp }RegularExpression Asserts that the target matches a regular expression.
|
.members(set) |
@param{ Array }set Asserts that the target is a superset of set, or that the target and set have the same strictly-equal (===) members. Alternately, if the deep flag is set, set members are compared for deep equality.
|
.most(value) |
@param{ Number }value Asserts that the target is less than or equal to value.
Can also be used in conjunction with length to assert a maximum length. The benefit being a more informative error message than if the length was supplied directly.
|
.not | Negates any of assertions following in the chain.
|
.null | Asserts that the target is null.
|
.ok | Asserts that the target is truthy. |
.ownProperty(name) |
@param{ String }name Asserts that the target has an own property name.
|
.property(name, [value]) |
@param{ String }name Asserts that the target has a property name, optionally asserting that the value of that property is strictly equal to value. If the deep flag is set, you can use dot- and bracket-notation for deep references into objects and arrays. // simple referencing
// deep referencing var deepObj = {
You can also use an array as the starting point of a deep.property assertion, or traverse nested arrays. var arr = [
Furthermore, property changes the subject of the assertion to be the value of that property from the original object. This permits for further chainable assertions on that property.
|
.respondTo(method) |
@param{ String }method Asserts that the object or class target will respond to a method. Klass.prototype.bar = function(){};
To check if a constructor will respond to a static function, set the itself flag. Klass.baz = function(){};
|
.satisfy(method) |
@param{ Function }matcher Asserts that the target passes a given truth test.
|
.string(string) |
@param{ String }string Asserts that the string target contains another string.
|
.throw(constructor) |
@param{ ErrorConstructor }constructor var err = new ReferenceError('This is a bad function.'); var fn = function () { throw err; }
|
.true | Asserts that the target is true.
|
.undefined | Asserts that the target is undefined.
|
.within(start, finish) |
@param{ Number }startlowerbound inclusive
Can also be used in conjunction with length to assert a length range. The benefit being a more informative error message than if the length was supplied directly.
|
links: sinon home , docs , code
var spy = sinon.spy();
Creates an anonymous function that records arguments, this value, exceptions and return values for all calls.
var spy = sinon.spy(myFunc);
Spies on the provided function
var spy = sinon.spy(object, "method");
Creates a spy for object.method and replaces the original method with the spy. The spy acts exactly like the original method in all cases. The original method can be restored by calling object.method.restore(). The returned spy is the function object which replaced the original method. spy === object.method.
Spy method | Description |
---|---|
spy.callCount | The number of recorded calls. |
spy.called | true if the spy was called at least once |
spy.calledOnce | true if spy was called exactly once |
spy.calledTwice | true if the spy was called exactly twice |
spy.calledThrice | true if the spy was called exactly thrice |
spy.firstCall | The first call |
spy.secondCall | The second call |
spy.thirdCall | The third call |
spy.lastCall | The last call |
spy.calledBefore(anotherSpy); | Returns true if the spy was called before anotherSpy |
spy.calledAfter(anotherSpy); | Returns true if the spy was called after anotherSpy |
spy.calledOn(obj); | Returns true if the spy was called at least once with obj as this |
spy.alwaysCalledOn(obj); | Returns true if the spy was always called with obj as this. |
spy.calledWith(arg1, arg2, ...); | Returns true if spy was called at least once with the provided arguments. Can be used for partial matching, Sinon only checks the provided arguments against actual arguments, so a call that received the provided arguments (in the same spots) and possibly others as well will return true. |
spy.alwaysCalledWith(arg1, arg2, ...); | Returns true if spy was always called with the provided arguments (and possibly others). |
spy.calledWithExactly(arg1, arg2, ...); | Returns true if spy was called at least once with the provided arguments and no others. |
spy.alwaysCalledWithExactly(arg1, arg2, ...); | Returns true if spy was always called with the exact provided arguments. |
spy.calledWithMatch(arg1, arg2, ...); | Returns true if spy was called with matching arguments (and possibly others). This behaves the same as spy.calledWith(sinon.match(arg1), sinon.match(arg2), ...). |
spy.alwaysCalledWithMatch(arg1, arg2, ...); | Returns true if spy was always called with matching arguments (and possibly others). This behaves the same as spy.alwaysCalledWith(sinon.match(arg1), sinon.match(arg2), ...). |
spy.calledWithNew(); | Returns true if spy/stub was called the new operator. Beware that this is inferred based on the value of the this object and the spy function’s prototype, so it may give false positives if you actively return the right kind of object. |
spy.neverCalledWith(arg1, arg2, ...); | Returns true if the spy/stub was never called with the provided arguments. |
spy.neverCalledWithMatch(arg1, arg2, ...); | Returns true if the spy/stub was never called with matching arguments. This behaves the same as spy.neverCalledWith(sinon.match(arg1), sinon.match(arg2), ...). |
spy.threw(); | Returns true if spy threw an exception at least once. |
spy.threw("TypeError"); | Returns true if spy threw an exception of the provided type at least once. |
spy.threw(obj); | Returns true if spy threw the provided exception object at least once. |
spy.alwaysThrew(); | Returns true if spy always threw an exception. |
spy.alwaysThrew("TypeError"); | Returns true if spy always threw an exception of the provided type. |
spy.alwaysThrew(obj); | Returns true if spy always threw the provided exception object. |
spy.returned(obj); | Returns true if spy returned the provided value at least once. Uses deep comparison for objects and arrays. Use spy.returned(sinon.match.same(obj)) for strict comparison (see Matchers). |
spy.alwaysReturned(obj); | Returns true if spy always returned the provided value. |
var spyCall = spy.getCall(n); | Returns the nth call). Accessing individual calls helps with more detailed behavior verification when the spy is called more than once. Example:
sinon.spy(jQuery, "ajax"); jQuery.ajax("/stuffs"); var spyCall = jQuery.ajax.getCall(0); assertEquals("/stuffs", spyCall.args[0]); |
spy.thisValues | Array of this objects, spy.thisValues[0] is the this object for the first call. |
spy.args | Array of arguments received, spy.args[0] is an array of arguments received in the first call. |
spy.exceptions | Array of exception objects thrown, spy.exceptions[0] is the exception thrown by the first call. If the call did not throw an error, the value at the call’s location in .exceptions will be ‘undefined’. |
spy.returnValues | Array of return values, spy.returnValues[0] is the return value of the first call. If the call did not explicitly return a value, the value at the call’s location in .returnValues will be ‘undefined’. |
spy.resetHistory() | Resets the state of a spy. |
spy.printf(format string", [arg1, arg2, ...])` | Returns the passed format string with the following replacements performed:
|
Spy method | Description |
---|---|
var spyCall = spy.getCall(n) | Returns the nth [call](#spycall). Accessing individual calls helps with more detailed behavior verification when the spy is called more than once. Example: |
spyCall.calledOn(obj); | Returns true if obj was this for this call. |
spyCall.calledWith(arg1, arg2, ...); | Returns true if call received provided arguments (and possibly others). |
spyCall.calledWithExactly(arg1, arg2, ...); | Returns true if call received provided arguments and no others. |
spyCall.calledWithMatch(arg1, arg2, ...); | Returns true if call received matching arguments (and possibly others). This behaves the same as spyCall.calledWith(sinon.match(arg1), sinon.match(arg2), ...). |
spyCall.notCalledWith(arg1, arg2, ...); | Returns true if call did not receive provided arguments. |
spyCall.notCalledWithMatch(arg1, arg2, ...); | Returns true if call did not receive matching arguments. This behaves the same as spyCall.notCalledWith(sinon.match(arg1), sinon.match(arg2), ...). |
spyCall.threw(); | Returns true if call threw an exception. |
spyCall.threw(TypeError"); | Returns true if call threw exception of provided type. |
spyCall.threw(obj); | Returns true if call threw provided exception object. |
spyCall.thisValue | The call’s this value. |
spyCall.args | Array of received arguments. |
spyCall.exception | Exception thrown, if any. |
spyCall.returnValue | Return value. |
link: stubs doc
var stub = sinon.stub();
Creates an anonymous stub function.
var stub = sinon.stub(object, "method");
Replaces object.method with a stub function. The original function can be restored by calling object.method.restore(); (or stub.restore();). An exception is thrown if the property is not already a function, to help avoid typos when stubbing methods.
var stub = sinon.stub(object, "method").callsFake(fn)
// deprecated (since v3.0.0): var stub = sinon.stub(object, "method", func);
Replaces object.method with a func, wrapped in a spy. As usual, object.method.restore(); can be used to restore the original method.
var stub = sinon.stub(obj);
Stubs all the object’s methods. Note that it’s usually better practice to stub individual methods, particularly on objects that you don’t understand or control all the methods for (e.g. library dependencies). Stubbing individual methods tests intent more precisely and is less susceptible to unexpected behavior as the object’s code evolves. If you want to create a stub object of MyConstructor, but don’t want the constructor to be invoked, use this utility function.
var stub = sinon.createStubInstance(MyConstructor)
Stub method | Description |
---|---|
stub.withArgs(arg1[, arg2, ...]); | Stubs the method only for the provided arguments. This is useful to be more expressive in your assertions, where you can access the spy with the same call. It is also useful to create a stub that can act differently in response to different arguments. |
stub.onCall(n); | Defines the behavior of the stub on the nth call. Useful for testing sequential interactions. |
stub.onFirstCall(); | Alias for stub.onCall(0); |
stub.onSecondCall(); | Alias for stub.onCall(1); |
stub.onThirdCall(); | Alias for stub.onCall(2); |
stub.returns(obj); | Makes the stub return the provided value. |
stub.returnsArg(index); | Causes the stub to return the argument at the provided index. stub.returnsArg(0); causes the stub to return the first argument. |
stub.returnsThis(); | Causes the stub to return its this value. Useful for stubbing jQuery-style fluent APIs. |
stub.resolves(value); |
Causes the stub to return a Promise which resolves to the provided value.
When constructing the Promise, sinon uses the Promise.resolve method. You are responsible for providing a polyfill in environments which do not provide Promise. The Promise library can be overwritten using the usingPromise method.
Since [email protected] |
stub.resolvesArg(index); |
Causes the stub to return a Promise which resolves to the argument at the provided index.
stub.resolvesArg(0); causes the stub to return a Promise which resolves to the first argument.
If the argument at the provided index is not available, a TypeError will be thrown.
Since [email protected] |
stub.throws(); | Causes the stub to throw an exception (Error). |
stub.throws("TypeError"); | Causes the stub to throw an exception of the provided type. |
stub.throws(obj); | Causes the stub to throw the provided exception object. |
stub.callsArg(index); | Causes the stub to call the argument at the provided index as a callback function. stub.callsArg(0); causes the stub to call the first argument as a callback. |
stub.callsArgOn(index, context); | Like above but with an additional parameter to pass the this context. |
stub.callsArgWith(index, arg1, arg2, ...); | Like callsArg, but with arguments to pass to the callback. |
stub.callsArgOnWith(index, context, arg1, arg2, ...); | Like above but with an additional parameter to pass the this context. |
stub.yields([arg1, arg2, ...]) | Almost like callsArg. Causes the stub to call the first callback it receives with the provided arguments (if any). If a method accepts more than one callback, you need to use callsArg to have the stub invoke other callbacks than the first one. |
stub.yieldsOn(context, [arg1, arg2, ...]) | Like above but with an additional parameter to pass the this context. |
stub.yieldsTo(property, [arg1, arg2, ...]) | Causes the spy to invoke a callback passed as a property of an object to the spy. Like yields, yieldsTo grabs the first matching argument, finds the callback and calls it with the (optional) arguments. |
stub.yieldsToOn(property, context, [arg1, arg2, ...]) | Like above but with an additional parameter to pass the this context. |
spy.yield([arg1, arg2, ...]) | Invoke callbacks passed to the spy with the given arguments. If the spy was never called with a function argument, yield throws an error. Also aliased as invokeCallback. |
spy.yieldTo(callback, [arg1, arg2, ...]) | Invokes callbacks passed as a property of an object to the spy. Like yield, yieldTo grabs the first matching argument, finds the callback and calls it with the (optional) arguments. |
spy.callArg(argNum) | Like yield, but with an explicit argument number specifying which callback to call. Useful if a function is called with more than one callback, and simply calling the first callback is not desired. |
spy.callArgWith(argNum, [arg1, arg2, ...]) | Like `callArg`, but with arguments. |
stub.callsArgAsync(index); | Same as their corresponding non-Async counterparts, but with callback being deferred (executed not immediately but after short timeout and in another “thread”) |
stub.callsArgOnAsync(index, context); | |
stub.callsArgWithAsync(index, arg1, arg2, ...); | |
stub.callsArgOnWithAsync(index, context, arg1, arg2, ...); | |
stub.yieldsAsync([arg1, arg2, ...]) | |
stub.yieldsOnAsync(context, [arg1, arg2, ...]) | |
stub.yieldsToAsync(property, [arg1, arg2, ...]) | |
stub.yieldsToOnAsync(property, context, [arg1, arg2, ...]) | Same as their corresponding non-Async counterparts, but with callback being deferred (executed not immediately but after short timeout and in another “thread”) |
link: docs
var mock = sinon.mock(obj);
Creates a mock for the provided object. Does not change the object, but returns a mock object to set expectations on the object’s methods.
var expectation = mock.expects("method");
Overrides obj.method with a mock function and returns it. See expectations below.
mock.restore();
Restores all mocked methods.
mock.verify();
Verifies all expectations on the mock. If any expectation is not satisfied, an exception is thrown. Also restores the mocked methods.
Expectation method | Description |
---|---|
var expectation = sinon.expectation.create([methodName]); | Creates an expectation without a mock object, basically an anonymous mock function. Method name is optional and is used in exception messages to make them more readable. |
var expectation = sinon.mock(); | The same as the above. |
expectation.atLeast(number); | Specify the minimum amount of calls expected. |
expectation.atMost(number); | Specify the maximum amount of calls expected. |
expectation.never(); | Expect the method to never be called. |
expectation.once(); | Expect the method to be called exactly once. |
expectation.twice(); | Expect the method to be called exactly twice. |
expectation.thrice(); | Expect the method to be called exactly thrice. |
expectation.exactly(number); | Expect the method to be called exactly number times. |
expectation.withArgs(arg1, arg2, ...); | Expect the method to be called with the provided arguments and possibly others. |
expectation.withExactArgs(arg1, arg2, ...); | Expect the method to be called with the provided arguments and no others. |
expectation.on(obj); | Expect the method to be called with obj as this. |
expectation.verify(); | Verifies the expectation and throws an exception if it’s not met. |
Matchers method | Description |
---|---|
sinon.match(number) | Requires the value to be == to the given number. |
sinon.match(string) | Requires the value to be a string and have the expectation as a substring. |
sinon.match(regexp) | Requires the value to be a string and match the given regular expression. |
sinon.match(object) | Requires the value to be not null or undefined and have at least the same properties as expectation. This supports nested matchers. |
sinon.match(function) | See [custom matchers](#sinonCustomMatchers) |
sinon.match.any | Matches anything. |
sinon.match.defined | Requires the value to be defined. |
sinon.match.truthy | Requires the value to be truthy. |
sinon.match.falsy | Requires the value to be falsy. |
sinon.match.bool | Requires the value to be a boolean. |
sinon.match.number | Requires the value to be a number. |
sinon.match.string | Requires the value to be a string. |
sinon.match.object | Requires the value to be an object. |
sinon.match.func | Requires the value to be a function. |
sinon.match.array | Requires the value to be an array. |
sinon.match.regexp | Requires the value to be a regular expression. |
sinon.match.date | Requires the value to be a date object. |
sinon.match.same(ref) | Requires the value to strictly equal ref. |
sinon.match.typeOf(type) | Requires the value to be of the given type, where type can be one of "undefined", "null", "boolean", "number", "string", "object", "function", "array", "regexp" or "date". |
sinon.match.instanceOf(type) | Requires the value to be an instance of the given type. |
sinon.match.has(property[, expectation]) | Requires the value to define the given property. The property might be inherited via the prototype chain. If the optional expectation is given, the value of the property is deeply compared with the expectation. The expectation can be another matcher. |
sinon.match.hasOwn(property[, expectation]) | Same as sinon.match.has but the property must be defined by the value itself. Inherited properties are ignored. |
All matchers implement and
and or
. This allows to logically combine mutliple matchers. The result is a new matchers that requires both (and) or one of the matchers (or) to return true.
var stringOrNumber = sinon.match.string.or(sinon.match.number);
var bookWithPages = sinon.match.instanceOf(Book).and(sinon.match.has("pages"));
Custom matchers are created with the sinon.match
factory which takes a test function and an optional message. The test function takes a value as the only argument, returns true
if the value matches the expectation and false
otherwise. The message string is used to generate the error message in case the value does not match the expectation.
var trueIsh = sinon.match(function (value) {
return !!value;
}, "trueIsh");
links: home
Method | Description |
---|---|
Synchronous code |
describe('Array', function(){ describe('#indexOf()', function(){ it('should return -1 when the value is not present', function(){ [1,2,3].indexOf(5).should.equal(-1); [1,2,3].indexOf(0).should.equal(-1); }) }) }) |
Asynchronous code |
describe('User', function(){ describe('#save()', function(){ it('should save without error', function(done){ var user = new User('Luna'); user.save(function(err){ if (err) throw err; done(); }); }) }) }) |
Done with Error | describe('User', function(){
describe('#save()', function(){
}) }) |
hooks |
describe('hooks', function() { before(function() { // runs before all tests in this block }) after(function(){ // runs after all tests in this block }) beforeEach(function(){ // runs before each test in this block }) afterEach(function(){ // runs after each test in this block }) // test cases }) Each hook also accepting done as first parameter to support async methods |
Pending tests | describe('Array', function(){ describe('#indexOf()', function(){ it('should return -1 when the value is not present'); }) }) |
Exclusive tests | describe('Array', function(){ describe.only('#indexOf()', function(){ ... }) }) Or a specific test-case: describe('Array', function(){ |
Inclusive tests | describe('Array', function(){ describe.skip('#indexOf()', function(){ ... }) }) Or a specific test-case: describe('Array', function(){ |
Usage:
mocha [debug] [options] [files]
Flag | Description |
---|---|
-w, --watch | Executes tests on changes to JavaScript in the CWD, and once initially. |
--compilers | coffee-script is no longer supported out of the box. CS and similar transpilers may be used by mapping the file extensions (for use with --watch) and the module name. For example --compilers coffee:coffee-script with CoffeeScript 1.6- or --compilers coffee:coffee-script/register with CoffeeScript 1.7+. |
-b, --bail | Only interested in the first exception? use --bail ! |
-d, --debug | Enables node's debugger support, this executes your script(s) with node debug allowing you to step through code and break with the debugger statement. Note the difference between mocha debug and mocha --debug: mocha debug will fire up node's built-in debug client, mocha --debug will allow you to use a different interface — such as the Blink Developer Tools. |
--globals [names] | Accepts a comma-delimited list of accepted global variable names. For example, suppose your app deliberately exposes a global named app and YUI, you may want to add --globals app,YUI. It also accepts wildcards. You could do --globals '*bar' and it would match foobar, barbar, etc. You can also simply pass in '*' to ignore all globals. |
--check-leaks | By default Mocha will not check for global variables leaked while running tests, to enable this pass --check-leaks, to specify globals that are acceptable use --globals, for example --globals jQuery,MyLib. |
-r, --require [name] | The --require option is useful for libraries such as should.js, so you may simply --require should instead of manually invoking require('should') within each test file. Note that this works well for should as it augments Object.prototype, however if you wish to access a module's exports you will have to require them, for example var should = require('should'). Furthermore, it can be used with relative paths, e.g. --require ./test/helper.js |
-u, --ui [name] | The --ui option lets you specify the interface to use, defaulting to "bdd". |
-R, --reporter [name] | The --reporter option allows you to specify the reporter that will be used, defaulting to "dot". This flag may also be used to utilize third-party reporters. For example if you npm install mocha-lcov-reporter you may then do --reporter mocha-lcov-reporter. |
-t, --timeout [ms] | Specifies the test-case timeout, defaulting to 2 seconds. To override you may pass the timeout in milliseconds, or a value with the s suffix, ex: --timeout 2s or --timeout 2000 would be equivalent. |
-s, --slow [ms] | Specify the "slow" test threshold, defaulting to 75ms. Mocha uses this to highlight test-cases that are taking too long. |
-g, --grep [pattern] | The --grep option when specified will trigger mocha to only run tests matching the given pattern which is internally compiled to a RegExp. |
Method | Description |
---|---|
afterAll(fn, timeout) | Runs a function after all the tests in this file have completed. If the function returns a promise or is a generator, Jest waits for that promise to resolve before continuing. Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait before aborting. Note: The default timeout is 5 seconds. This is often useful if you want to clean up some global setup state that is shared across tests. |
afterEach(fn, timeout) | Runs a function after each one of the tests in this file completes. If the function returns a promise or is a generator, Jest waits for that promise to resolve before continuing. Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait before aborting. Note: The default timeout is 5 seconds. This is often useful if you want to clean up some temporary state that is created by each test. |
beforeAll(fn, timeout) | Runs a function before any of the tests in this file run. If the function returns a promise or is a generator, Jest waits for that promise to resolve before running tests. Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait before aborting. Note: The default timeout is 5 seconds. This is often useful if you want to set up some global state that will be used by many tests. |
beforeEach(fn, timeout) | Runs a function before each of the tests in this file runs. If the function returns a promise or is a generator, Jest waits for that promise to resolve before running the test. Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait before aborting. Note: The default timeout is 5 seconds. This is often useful if you want to reset some global state that will be used by many tests. |
describe(name, fn) | describe(name, fn) creates a block that groups together several related tests. For example, if you have a myBeverage object that is supposed to be delicious but not sour, you could test it with: |
describe.each(table)(name, fn, timeout) |
Use describe.each if you keep duplicating the same test suites with different data. describe.each allows you to write the test suite once and pass data in.
describe.each is available with two APIs 1. table: Array of Arrays with the arguments that are passed into the fn for each row. Note If you pass in a 1D array of primitives, internally it will be mapped to a table i.e. [1, 2, 3] -> [[1], [2], [3]] name: String the title of the test suite. Generate unique test titles by positionally injecting parameters with printf formatting. 2. describe.each`table`(name, fn, timeout) full doc |
describe.only(name, fn) | Also under the alias: fdescribe(name, fn) You can use describe.only if you want to run only one describe block: |
describe.only.each(table)(name, fn) |
Also under the aliases: fdescribe.each(table)(name, fn) and fdescribe.each`table`(name, fn)
Use describe.only.each if you want to only run specific tests suites of data driven tests.
describe.only.each is available with two APIs: full doc |
describe.skip(name, fn) | Also under the alias: xdescribe(name, fn) You can use describe.skip if you do not want to run a particular describe block: |
describe.skip.each(table)(name, fn) |
Also under the aliases: xdescribe.each(table)(name, fn) and xdescribe.each`table`(name, fn)
Use describe.skip.each if you want to stop running a suite of data driven tests.
describe.skip.each is available with two APIs: full doc |
test(name, fn, timeout) |
Also under the alias: it(name, fn, timeout)
All you need in a test file is the test method which runs a test. For example, let's say there's a function inchesOfRain() that should be zero. Your whole test could be:
The first argument is the test name; the second argument is a function that contains the expectations to test. The third argument (optional) is timeout (in milliseconds) for specifying how long to wait before aborting. Note: The default timeout is 5 seconds. Note: If a promise is returned from test, Jest will wait for the promise to resolve before letting the test complete. Jest will also wait if you provide an argument to the test function, usually called done. This could be handy when you want to test callbacks. |
test.concurrent(name, fn, timeout) |
Also under the alias: it.concurrent(name, fn, timeout)
Use test.concurrent if you want the test to run concurrently.
The first argument is the test name; the second argument is an asynchronous function that contains the expectations to test. The third argument (optional) is timeout (in milliseconds) for specifying how long to wait before aborting. Note: The default timeout is 5 seconds. |
test.concurrent.each(table)(name, fn, timeout) |
Also under the alias: it.concurrent.each(table)(name, fn, timeout)
Use test.concurrent.each if you keep duplicating the same test with different data. test.each allows you to write the test once and pass data in, the tests are all run asynchronously.
test.concurrent.each is available with two APIs: 1. test.concurrent.each(table)(name, fn, timeout) 2. test.concurrent.each`table`(name, fn, timeout) full doc |
test.concurrent.only.each(table)(name, fn) |
Also under the alias: it.concurrent.only.each(table)(name, fn)
Use test.concurrent.only.each if you want to only run specific tests with different test data concurrently. full doc |
test.concurrent.skip.each(table)(name, fn) |
Also under the alias: it.concurrent.skip.each(table)(name, fn)
Use test.concurrent.skip.each if you want to stop running a collection of asynchronous data driven tests. full doc |
test.each(table)(name, fn, timeout) |
Also under the alias: it.each(table)(name, fn) and it.each`table`(name, fn)
Use test.each if you keep duplicating the same test with different data. test.each allows you to write the test once and pass data in.
test.each is available with two APIs: 1. test.each(table)(name, fn, timeout) 2. test.each`table`(name, fn, timeout) full doc |
test.only(name, fn, timeout) | Also under the aliases: it.only(name, fn, timeout), and fit(name, fn, timeout) When you are debugging a large test file, you will often only want to run a subset of tests. You can use .only to specify which tests are the only ones you want to run in that test file. Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait before aborting. Note: The default timeout is 5 seconds. |
test.only.each(table)(name, fn) |
Also under the aliases: it.only.each(table)(name, fn), fit.each(table)(name, fn), it.only.each`table`(name, fn) and fit.each`table`(name, fn)
Use test.only.each if you want to only run specific tests with different test data.
test.only.each is available with two APIs: full doc |
test.skip(name, fn) | Also under the aliases: it.skip(name, fn), xit(name, fn), and xtest(name, fn) When you are maintaining a large codebase, you may sometimes find a test that is temporarily broken for some reason. If you want to skip running this test, but you don't want to delete this code, you can use test.skip to specify some tests to skip. |
test.skip.each(table)(name, fn) |
Also under the aliases: it.skip.each(table)(name, fn), xit.each(table)(name, fn), xtest.each(table)(name, fn), it.skip.each`table`(name, fn), xit.each`table`(name, fn) and xtest.each`table`(name, fn)
Use test.skip.each if you want to stop running a collection of data driven tests.
test.skip.each is available with two APIs: full doc |
test.todo(name) | Also under the alias: it.todo(name) Use test.todo when you are planning on writing tests. These tests will be highlighted in the summary output at the end so you know how many tests you still need todo. Note: If you supply a test callback function then the test.todo will throw an error. If you have already implemented the test and it is broken and you do not want it to run, then use test.skip instead. |
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 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.
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');
});
Use resolves to unwrap the value of a fulfilled promise so any other matcher can be chained. If the promise is rejected the assertion fails.
For example, this code tests that the promise resolves and that the resulting value is 'lemon':
test('resolves to lemon', () => {
// make sure to add a return statement
return expect(Promise.resolve('lemon')).resolves.toBe('lemon');
});
Use .rejects to unwrap the reason of a rejected promise so any other matcher can be chained. If the promise is fulfilled the assertion fails.
For example, this code tests that the promise rejects with reason 'octopus':
test('rejects to octopus', () => {
// make sure to add a return statement
return expect(Promise.reject(new Error('octopus'))).rejects.toThrow(
'octopus',
);
});
Method | Description |
---|---|
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 utility library and you're frequently asserting that numbers appear within particular ranges of other numbers. You could abstract that into a toBeWithinRange matcher: |
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: |
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: |
expect.arrayContaining(array) |
matches a received array which contains all of the elements in the expected array. That is, the expected array is a subset of the received array. Therefore, it matches a received array which contains elements that are not in the expected array.
You can use it instead of a literal value:
- in toEqual or toBeCalledWith - to match a property in objectContaining or toMatchObject expect.not.arrayContaining(array) matches a received array which does not contain all of the elements in the expected array. That is, the expected array is not a subset of the received array. |
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 function doAsync that receives two callbacks callback1 and callback2, it will asynchronously call both of them in an unknown order. We can test this with: |
expect.hasAssertions() | verifies that at least one assertion is 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: |
expect.objectContaining(object) |
matches any received object that recursively matches the expected properties. That is, the expected object is a subset of the received object. Therefore, it matches a received object which contains properties that are present in the expected object.
Instead of literal property values in the expected object, you can use matchers, expect.anything(), and so on.
expect.not.objectContaining(object) matches any received object that does not recursively match the expected properties. That is, the expected object is not a subset of the received object. Therefore, it matches a received object which contains properties that are not in the expected object. |
expect.stringContaining(string) |
matches the received value if it is a string that contains the exact expected string.
expect.not.stringContaining(string) matches the received value if it is not a string or if it is a string that does not contain the exact expected string. |
expect.stringMatching(string | regexp) |
matches the received value if it is a string that matches the expected string or regular expression.
You can use it instead of a literal value:
-in toEqual or toBeCalledWith - to match an element in arrayContaining - to match a property in objectContaining or toMatchObject expect.not.stringMatching(string | regexp) matches the received value if it is not a string or if it is a string that does not match the expected string or regular expression. |
expect.addSnapshotSerializer(serializer) |
You can call expect.addSnapshotSerializer to add a module that formats application-specific data structures.
For an individual test file, an added module precedes any modules from snapshotSerializers configuration, which precede the default snapshot serializers for built-in JavaScript types and for React elements. The last module added is the first module tested.
full doc |
.toBe(value) |
Use .toBe to compare primitive values or to check referential identity of object instances. It calls Object.is to compare values, which is even better for testing than === strict equality operator.
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. Although the .toBe matcher checks referential identity, it reports a deep comparison of values if the assertion fails. If differences between properties do not help you to understand why a test fails, especially if the report is large, then you might move the comparison into the expect function. For example, to assert whether or not elements are the same instance: rewrite expect(received).toBe(expected) as expect(Object.is(received, expected)).toBe(true) rewrite expect(received).not.toBe(expected) as expect(Object.is(received, expected)).toBe(false) |
.toHaveBeenCalled() | Also under the alias: .toBeCalled() Use .toHaveBeenCalled to ensure that a mock function got called. |
.toHaveBeenCalledTimes(number) | Also under the alias: .toBeCalledTimes(number) Use .toHaveBeenCalledTimes to ensure that a mock function got called exact number of times. |
.toHaveBeenCalledWith(arg1, arg2, ...) | Also under the alias: .toBeCalledWith() Use .toHaveBeenCalledWith to ensure that a mock function was called with specific arguments. |
.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. |
.toHaveBeenNthCalledWith(nthCall, arg1, arg2, ....) | Also under the alias: .nthCalledWith(nthCall, arg1, arg2, ...) If you have a mock function, you can use .toHaveBeenNthCalledWith to test what arguments it was nth called with |
.toHaveReturned() | Also under the alias: .toReturn() If you have a mock function, you can use .toHaveReturned to test that the mock function successfully returned (i.e., did not throw an error) at least one time. |
.toHaveReturnedTimes(number) | lso under the alias: .toReturnTimes(number) Use .toHaveReturnedTimes to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times. Any calls to the mock function that throw an error are not counted toward the number of times the function returned. |
.toHaveReturnedWith(value) | Also under the alias: .toReturnWith(value) Use .toHaveReturnedWith to ensure that a mock function returned a specific value. |
.toHaveLastReturnedWith(value) | Also under the alias: .lastReturnedWith(value) Use .toHaveLastReturnedWith to test the specific value that a mock function last returned. If the last call to the mock function threw an error, then this matcher will fail no matter what value you provided as the expected return value. |
.toHaveNthReturnedWith(nthCall, value) | Also under the alias: .nthReturnedWith(nthCall, value) Use .toHaveNthReturnedWith to test the specific value that a mock function returned for the nth call. If the nth call to the mock function threw an error, then this matcher will fail no matter what value you provided as the expected return value. |
.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. |
.toHaveProperty(keyPath, value?) | Use .toHaveProperty to check if property at provided reference keyPath exists for an object. For checking deeply nested properties in an object you may use dot notation or an array containing the keyPath for deep references. You can provide an optional value argument to compare the received property value (recursively for all properties of object instances, also known as deep equality, like the toEqual matcher). |
.toBeCloseTo(number, numDigits?) |
Use toBeCloseTo to compare floating point numbers for approximate equality.
The optional numDigits argument limits the number of digits to check after the decimal point. For the default value 2, the test criterion is Math.abs(expected - received) < 0.005 (that is, 10 ** -2 / 2).
Intuitive equality comparisons often fail, because arithmetic on decimal (base 10) values often have rounding errors in limited precision binary (base 2) representation
* Because floating point errors are the problem that toBeCloseTo solves, it does not support big integer values. |
.toBeDefined() | Use .toBeDefined to check that a variable is not undefined. For example, if you want to check that a function fetchNewFlavorIdea() returns something, you can write: |
.toBeFalsy() | Use .toBeFalsy when you don't care what a value is and you want to ensure a value is false in a boolean context. In JavaScript, there are six falsy values: false, 0, '', null, undefined, and NaN. Everything else is truthy. |
.toBeGreaterThan(number | bigint) | Use toBeGreaterThan to compare received > expected for number or big integer values. |
.toBeGreaterThanOrEqual(number | bigint) | Use toBeGreaterThanOrEqual to compare received >= expected for number or big integer values. |
.toBeLessThan(number | bigint) | Use toBeLessThan to compare received < expected for number or big integer values |
.toBeLessThanOrEqual(number | bigint) | Use toBeLessThanOrEqual to compare received <= expected for number or big integer values |
.toBeInstanceOf(Class) | Use .toBeInstanceOf(Class) to check that an object is an instance of a class |
.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. |
.toBeTruthy() | Use .toBeTruthy when you don't care what a value is and you want to ensure a value is true in a boolean context |
.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: |
.toBeNaN() | Use .toBeNaN when checking a value is NaN |
.toContain(item) | Use .toContain when you want to check that an item is in an array. For testing the items in the array, this uses ===, a strict equality check. .toContain can also check whether a string is a substring of another string. |
.toContainEqual(item) | Use .toContainEqual when you want to check that an item with a specific structure and values is contained in an array. For testing the items in the array, this matcher recursively checks the equality of all fields, rather than checking for object identity. |
.toEqual(value) |
Use .toEqual to compare recursively all properties of object instances (also known as "deep" equality). It calls Object.is to compare primitive values, which is even better for testing than === strict equality operator.
Note: .toEqual won't perform a deep equality check for two errors. Only the message property of an Error is considered for equality. It is recommended to use the .toThrow matcher for testing against errors. |
.toMatch(regexpOrString) | Use .toMatch to check that a string matches a regular expression. |
.toMatchObject(object) |
Use .toMatchObject to check that a JavaScript object matches a subset of the properties of an object. It will match received objects with properties that are not in the expected object.
You can also pass an array of objects, in which case the method will return true only if each object in the received array matches (in the toMatchObject sense described above) the corresponding object in the expected array. This is useful if you want to check that two arrays match in their number of elements, as opposed to arrayContaining, which allows for extra elements in the received array. |
.toMatchSnapshot(propertyMatchers?, hint?) |
This ensures that a value matches the most recent snapshot. Check out the Snapshot Testing guide for more information.
You can provide an optional propertyMatchers object argument, which has asymmetric matchers as values of a subset of expected properties, if the received value will be an object instance. It is like toMatchObject with flexible criteria for a subset of properties, followed by a snapshot test as exact criteria for the rest of the properties. You can provide an optional hint string argument that is appended to the test name. Although Jest always appends a number at the end of a snapshot name, short descriptive hints might be more useful than numbers to differentiate multiple snapshots in a single it or test block. Jest sorts snapshots by name in the corresponding .snap file. |
.toMatchInlineSnapshot(propertyMatchers?, inlineSnapshot) |
Ensures that a value matches the most recent snapshot.
You can provide an optional propertyMatchers object argument, which has asymmetric matchers as values of a subset of expected properties, if the received value will be an object instance. It is like toMatchObject with flexible criteria for a subset of properties, followed by a snapshot test as exact criteria for the rest of the properties. Jest adds the inlineSnapshot string argument to the matcher in the test file (instead of an external .snap file) the first time that the test runs. Check out the section on Inline Snapshots for more info. |
.toStrictEqual(value) |
Use .toStrictEqual to test that objects have the same types as well as structure.
Differences from .toEqual:
|
.toThrow(error?) |
Also under the alias: .toThrowError(error?)
Use .toThrow to test that a function throws when it is calle
Note: You must wrap the code in a function, otherwise the error will not be caught and the assertion will fail. You can provide an optional argument to test that a specific error is thrown:
|
.toThrowErrorMatchingSnapshot(hint?) | Use .toThrowErrorMatchingSnapshot to test that a function throws an error matching the most recent snapshot when it is called. You can provide an optional hint string argument that is appended to the test name. Although Jest always appends a number at the end of a snapshot name, short descriptive hints might be more useful than numbers to differentiate multiple snapshots in a single it or test block. Jest sorts snapshots by name in the corresponding .snap file. |
.toThrowErrorMatchingInlineSnapshot(inlineSnapshot) | Use .toThrowErrorMatchingInlineSnapshot to test that a function throws an error matching the most recent snapshot when it is called. Jest adds the inlineSnapshot string argument to the matcher in the test file (instead of an external .snap file) the first time that the test runs |
Mock functions are also known as "spies", because they let you spy on the behavior of a function that is called indirectly by some other code, rather than only testing the output. You can create a mock function with jest.fn(). If no implementation is given, the mock function will return undefined when invoked.
Prop/Method | Description |
---|---|
mockFn.getMockName() | Returns the mock name string set by calling mockFn.mockName(value). |
mockFn.mock.calls | An array containing the call arguments of all calls that have been made to this mock function. Each item in the array is an array of arguments that were passed during the call. |
mockFn.mock.results |
An array containing the results of all calls that have been made to this mock function. Each entry in this array is an object containing a type property, and a value property. type will be one of the following:
|
mockFn.mock.instances | An array that contains all the object instances that have been instantiated from this mock function using new. |
mockFn.mockClear() |
Resets all information stored in the mockFn.mock.calls and mockFn.mock.instances arrays.
Often this is useful when you want to clean up a mock's usage data between two assertions.
Beware that mockClear will replace mockFn.mock, not just mockFn.mock.calls and mockFn.mock.instances. You should, therefore, avoid assigning mockFn.mock to other variables, temporary or not, to make sure you don't access stale data. The clearMocks configuration option is available to clear mocks automatically between tests. |
mockFn.mockReset() |
Does everything that mockFn.mockClear() does, and also removes any mocked return values or implementations.
This is useful when you want to completely reset a mock back to its initial state. (Note that resetting a spy will result in a function with no return value).
Beware that mockReset will replace mockFn.mock, not just mockFn.mock.calls and mockFn.mock.instances. You should, therefore, avoid assigning mockFn.mock to other variables, temporary or not, to make sure you don't access stale data. |
mockFn.mockRestore() |
Does everything that mockFn.mockReset() does, and also restores the original (non-mocked) implementation.
This is useful when you want to mock functions in certain test cases and restore the original implementation in others.
Beware that mockFn.mockRestore only works when the mock was created with jest.spyOn. Thus you have to take care of restoration yourself when manually assigning jest.fn(). The restoreMocks configuration option is available to restore mocks automatically between tests. |
mockFn.mockImplementation(fn) |
Accepts a function that should be used as the implementation of the mock. The mock itself will still record all calls that go into and instances that come from itself – the only difference is that the implementation will also be executed when the mock is called.
Note: jest.fn(implementation) is a shorthand for jest.fn().mockImplementation(implementation). |
mockFn.mockImplementationOnce(fn) |
Accepts a function that will be used as an implementation of the mock for one call to the mocked function. Can be chained so that multiple function calls produce different results.
When the mocked function runs out of implementations defined with mockImplementationOnce, it will execute the default implementation set with jest.fn(() => defaultValue) or .mockImplementation(() => defaultValue) if they were called: |
mockFn.mockName(value) | Accepts a string to use in test result output in place of "jest.fn()" to indicate which mock function is being referenced. |
mockFn.mockReturnThis() |
Syntactic sugar function for:
jest.fn(function () { return this; }); |
mockFn.mockReturnValue(value) | Accepts a value that will be returned whenever the mock function is called. |
mockFn.mockReturnValueOnce(value) | Accepts a value that will be returned for one call to the mock function. Can be chained so that successive calls to the mock function return different values. When there are no more mockReturnValueOnce values to use, calls will return a value specified by mockReturnValue. |
mockFn.mockResolvedValue(value) |
Syntactic sugar function for:
jest.fn().mockImplementation(() => Promise.resolve(value)); |
mockFn.mockResolvedValueOnce(value) |
Syntactic sugar function for:
jest.fn().mockImplementationOnce(() => Promise.resolve(value)); |
mockFn.mockRejectedValue(value) |
Syntactic sugar function for:
jest.fn().mockImplementation(() => Promise.reject(value)); |
mockFn.mockRejectedValueOnce(value) |
Syntactic sugar function for:
jest.fn().mockImplementationOnce(() => Promise.reject(value)); |
The jest object is automatically in scope within every test file. The methods in the jest object help create mocks and let you control Jest's overall behavior. It can also be imported explicitly by via import {jest} from '@jest/globals'.
Method | Description |
---|---|
jest.disableAutomock() | Disables automatic mocking in the module loader. Returns the jest object for chaining. |
jest.enableAutomock() | Enables automatic mocking in the module loader. Returns the jest object for chaining. |
jest.createMockFromModule(moduleName) |
Also under the alias: .genMockFromModule(moduleName)
Given the name of a module, use the automatic mocking system to generate a mocked version of the module for you.
full doc |
jest.mock(moduleName, factory, options) |
Mocks a module with an auto-mocked version when it is being required. factory and options are optional
The second argument can be used to specify an explicit module factory that is being run instead of using Jest's automocking feature: The third argument can be used to create virtual mocks – mocks of modules that don't exist anywhere in the system Returns the jest object for chaining. |
jest.unmock(moduleName) |
Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module).
The most common use of this API is for specifying the module a given test intends to be testing (and thus doesn't want automatically mocked).
Returns the jest object for chaining. |
jest.doMock(moduleName, factory, options) |
When using babel-jest, calls to mock will automatically be hoisted to the top of the code block. Use this method if you want to explicitly avoid this behavior.
Returns the jest object for chaining. |
jest.dontMock(moduleName) |
When using babel-jest, calls to unmock will automatically be hoisted to the top of the code block. Use this method if you want to explicitly avoid this behavior.
Returns the jest object for chaining. |
jest.setMock(moduleName, moduleExports) |
Explicitly supplies the mock object that the module system should return for the specified module.
On occasion, there are times where the automatically generated mock the module system would normally provide you isn't adequate enough for your testing needs. Normally under those circumstances you should write a manual mock that is more adequate for the module in question. However, on extremely rare occasions, even a manual mock isn't suitable for your purposes and you need to build the mock yourself inside your test. Note It is recommended to use jest.mock() instead. The jest.mock API's second argument is a module factory instead of the expected exported module object. Returns the jest object for chaining. |
jest.requireActual(moduleName) | Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not. |
jest.requireMock(moduleName) | Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not. |
jest.resetModules() |
Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests.
Returns the jest object for chaining. |
jest.isolateModules(fn) | jest.isolateModules(fn) goes a step further than jest.resetModules() and creates a sandbox registry for the modules that are loaded inside the callback function. This is useful to isolate specific modules for every test so that local module state doesn't conflict between tests. |
jest.fn(implementation) | Returns a new, unused mock function. Optionally takes a mock implementation. |
jest.isMockFunction(fn) | Determines if the given function is a mocked function. |
jest.spyOn(object, methodName) |
Creates a mock function similar to jest.fn but also tracks calls to object[methodName]. Returns a Jest mock function.
Note: By default, jest.spyOn also calls the spied method. This is different behavior from most other test libraries. If you want to overwrite the original function, you can use jest.spyOn(object, methodName).mockImplementation(() => customImplementation) or object[methodName] = jest.fn(() => customImplementation); |
jest.spyOn(object, methodName, accessType?) | Since Jest 22.1.0+, the jest.spyOn method takes an optional third argument of accessType that can be either 'get' or 'set', which proves to be useful when you want to spy on a getter or a setter, respectively. |
jest.clearAllMocks() |
Clears the mock.calls and mock.instances properties of all mocks. Equivalent to calling .mockClear() on every mocked function.
Returns the jest object for chaining. |
jest.resetAllMocks() |
Resets the state of all mocks. Equivalent to calling .mockReset() on every mocked function.
Returns the jest object for chaining. |
jest.restoreAllMocks() | Restores all mocks back to their original value. Equivalent to calling .mockRestore() on every mocked function. Beware that jest.restoreAllMocks() only works when the mock was created with jest.spyOn; other mocks will require you to manually restore them. |
jest.useFakeTimers(implementation?: 'modern' | 'legacy') |
Instructs Jest to use fake versions of the standard timer functions (setTimeout, setInterval, clearTimeout, clearInterval, nextTick, setImmediate and clearImmediate).
If you pass 'modern' as an argument, @sinonjs/fake-timers will be used as implementation instead of Jest's own fake timers. This also mocks additional timers like Date. 'modern' will be the default behavior in Jest 27. Returns the jest object for chaining. |
jest.useRealTimers() |
Instructs Jest to use the real versions of the standard timer functions.
Returns the jest object for chaining. |
jest.runAllTicks() |
Exhausts the micro-task queue (usually interfaced in node via process.nextTick).
When this API is called, all pending micro-tasks that have been queued via process.nextTick will be executed. Additionally, if those micro-tasks themselves schedule new micro-tasks, those will be continually exhausted until there are no more micro-tasks remaining in the queue. |
jest.runAllTimers() |
Exhausts both the macro-task queue (i.e., all tasks queued by setTimeout(), setInterval(), and setImmediate()) and the micro-task queue (usually interfaced in node via process.nextTick).
When this API is called, all pending macro-tasks and micro-tasks will be executed. If those tasks themselves schedule new tasks, those will be continually exhausted until there are no more tasks remaining in the queue. This is often useful for synchronously executing setTimeouts during a test in order to synchronously assert about some behavior that would only happen after the setTimeout() or setInterval() callbacks executed. See the Timer mocks doc for more information. |
jest.runAllImmediates() |
Exhausts all tasks queued by setImmediate().
Note: This function is not available when using modern fake timers implementation |
jest.advanceTimersByTime(msToRun) |
Also under the alias: .runTimersToTime()
Executes only the macro task queue (i.e. all tasks queued by setTimeout() or setInterval() and setImmediate()). When this API is called, all timers are advanced by msToRun milliseconds. All pending "macro-tasks" that have been queued via setTimeout() or setInterval(), and would be executed within this time frame will be executed. Additionally, if those macro-tasks schedule new macro-tasks that would be executed within the same time frame, those will be executed until there are no more macro-tasks remaining in the queue, that should be run within msToRun milliseconds. |
jest.runOnlyPendingTimers() |
Executes only the macro-tasks that are currently pending (i.e., only the tasks that have been queued by setTimeout() or setInterval() up to this point). If any of the currently pending macro-tasks schedule new macro-tasks, those new tasks will not be executed by this call.
This is useful for scenarios such as one where the module being tested schedules a setTimeout() whose callback schedules another setTimeout() recursively (meaning the scheduling never stops). In these scenarios, it's useful to be able to run forward in time by a single step at a time. |
jest.advanceTimersToNextTimer(steps) | Advances all timers by the needed milliseconds so that only the next timeouts/intervals will run. Optionally, you can provide steps, so it will run steps amount of next timeouts/intervals. |
jest.clearAllTimers() | Removes any pending timers from the timer system. This means, if any timers have been scheduled (but have not yet executed), they will be cleared and will never have the opportunity to execute in the future. |
jest.getTimerCount() | Returns the number of fake timers still left to run. |
jest.setSystemTime(now?: number | Date) |
Set the current system time used by fake timers. Simulates a user changing the system clock while your program is running. It affects the current time but it does not in itself cause e.g. timers to fire; they will fire exactly as they would have done without the call to jest.setSystemTime().
Note: This function is only available when using modern fake timers implementation |
jest.getRealSystemTime() |
When mocking time, Date.now() will also be mocked. If you for some reason need access to the real current time, you can invoke this function.
Note: This function is only available when using modern fake timers implementation |
jest.setTimeout(timeout) |
Set the default timeout interval for tests and before/after hooks in milliseconds. This only affects the test file from which this function is called.
Note: The default timeout interval is 5 seconds if this method is not called. Note: If you want to set the timeout for all test files, a good place to do this is in setupFilesAfterEnv |
jest.retryTimes() |
Runs failed tests n-times until they pass or until the max number of retries is exhausted. This only works with jest-circus!
Returns the jest object for chaining. |