Preparation conditions
Build on the directories and code created in the tutorial in Section 1. If you haven’t seen the tutorial in Part 1, follow me and check out previous articles in this series. Before we get to the matchers, we’ll cover the basic code in index.test.js from the previous section
The import {sum} from '. / index test (' test sum, () = > {expect (sum (1, 2)). The place (3)})Copy the code
test
The method we call thetaThe test caseThe first argument is the name of the test, and the second argument is a function inside which you can write some test logicexpect
As the name suggests, it means expectation,expect(sum(1, 2)).toBe(3)
That means expect thissum(1, 2)
Returns the value and3
Equal, the whole thing is called thetaassertionstoBe
It’s a matcher, and whether the value of expect matches the value in the matcher is the subject of today’s lecture
Now that we know what the code we wrote earlier means, we’ll start with today’s topic matchers, which can be copied to index.test.js for testing
In order not to enable the command every timenpm run test
, can be inpackage.json
Add –watchAll to the test command so that file changes can be automatically retested
. ToBe (value) : matching value, equivalent to ===
const can = {
name: 'pamplemousse'
};
test('has a sophisticated name', () => {
expect(can.name).toBe('pamplemousse');
});
Copy the code
Note:
- Cannot be used to test floating point numbers for example
Expect (0.1 + 0.2). The place (0.3)
, you can use it if you need totoBeCloseTo
- Cannot be used for checking reference types
.toequal (value) : matches only the content but not the reference. It can be used to match the reference type
const can1 = {
flavor: 'grapefruit',
ounces: 12,
};
const can2 = {
flavor: 'grapefruit',
ounces: 12,
};
test('have all the same properties', () => {
expect(can1).toEqual(can2);
});
Copy the code
Note:
- Cannot be used to match two thrown exceptions
.tobenull () : matches null
function bloop() {
return null;
}
test('bloop returns null', () => {
expect(bloop()).toBeNull();
});
Copy the code
Note:
- .tobenull () has the same effect as.tobe (null)
.tobeundefined () : matches undefined
test('test undefined', () => {
let name
let age = undefined
expect(name).toBeUndefined()
expect(age).toBeUndefined()
})
Copy the code
Note:
- .tobe undefined () and.tobe undefined () have the same effect
.tobenan () : matches NaN
test('passes when value is NaN', () => {
expect(NaN).toBeNaN();
});
Copy the code
.tobetruthy () : matches a value whose result is true
test('test true', () => { let name = 'Jsoning' let tag = true let age = 26 let obj = {} expect(name).toBeTruthy() expect(tag).toBeTruthy() expect(age).toBeTruthy() expect(obj).toBeTruthy() })Copy the code
Note:
- In js
false
.0
.' '
.null
.undefined
.NaN
Is automatically converted to false
.tobefalsy () : matches a value whose result is false
test('test false', () => { let name = null let tag = false let age = 0 let str = '' let und = undefined let nan = NaN expect(name).toBeFalsy() expect(tag).toBeFalsy() expect(age).toBeFalsy() expect(str).toBeFalsy() expect(und).toBeFalsy() expect(nan).toBeFalsy() })Copy the code
Note:
- In js
false
.0
.' '
.null
.undefined
.NaN
Is automatically converted to false
.tobeDefined () : Matches defined values
test('test toBeDefined', () => {
let name = ''
let age = 26
expect(name).toBeDefined()
expect(age).toBeDefined()
})
Copy the code
. Not: Reverses subsequent matches
test('test not', () => {let name = 'Jsoning' let n = null expect(name).tobe ('Jsoning') expect(name).tobe ('Json') // The matching value is not Json Expect (n).tobenull () expect(n).not. ToBeUndefined ()})Copy the code
. ToBeGreaterThan (number) : matches the number greater than number
test('test toBeGreaterThan', () => {
expect(10).toBeGreaterThan(9)
})
Copy the code
ToBeGreaterThanOrEqual (number) : matches the number greater than or equal to number
test('test toBeGreaterThanOrEqual', () => {
expect(10).toBeGreaterThanOrEqual(9)
expect(10).toBeGreaterThanOrEqual(10)
})
Copy the code
. ToBeLessThan (number) : matches the number less than number
test('test toBeLessThan', () => {
expect(1).toBeLessThan(2)
})
Copy the code
ToBeLessThanOrEqual (number) : matches the number less than or equal to number
test('test toBeLessThanOrEqual', () => {
expect(1).toBeLessThanOrEqual(1)
expect(1).toBeLessThanOrEqual(2)
})
Copy the code
.toBeCloseTo(number, numDigits?) : a floating point number that matches the specified number of bits
Test ('test toBeCloseTo', () => {// 0.1+0.2 = 0.30000000000000004 expect(0.1+0.2).tobecloseto (0.3, 5) // match 5 decimal digits})Copy the code
.tomatch (regexpOrString) : Checks whether strings match
test('test toMatch', () => {
let str = 'abcdefg'
expect(str).toMatch('ab')
expect(str).toMatch(/[a-z]/)
})
Copy the code
.tomatchObject (object) : Matches whether objects/arrays belong to subsets
test('test toMatchObject', () => {
let obj = {
name: 'Jsoning',
age: 24,
area: 'bj'
}
let arr = [
{
foo: 'bar',
name: 'Jsoning'
},
{
baz: 1,
age: 24
}
]
expect(obj).toMatchObject({
name: 'Jsoning'
})
expect(obj).toMatchObject({
name: 'Jsoning',
age: 24,
area: 'bj'
})
expect(arr).toMatchObject([
{
foo: 'bar'
},
{
baz: 1
}
])
})
Copy the code
.tocontain (item) : matches whether an array /Set/ string contains an item
test('test toContain', () => {
let name = 'Jsoning'
let arr = ['Jsoning', 'age']
let set = new Set(arr)
expect(name).toContain('Json')
expect(arr).toContain('Jsoning')
expect(set).toContain('age')
})
Copy the code
Note:
- Can’t check objects in arr/set, such as [{name: ‘Jsoning’}]
.toContainEqual(item) : similar to.tocontain, it must match exactly, but can match objects in an array
test('test toContainEqual', () => { let name = 'Jsoning' let arr = ['Jsoning', 'age', { name: 'Jsoning', age: 24}] let set = new set (arr) // expect(name).tocontainEqual ('Json') expect(set).toContainEqual('age') //expect(set).toContainEqual({ name: ToContainEqual ({name: 'Jsoning', age: 24})})Copy the code
ToHaveLength (number) : checks whether the object has the length attribute and checks whether it matches
test('test toHaveLength', () => {
expect([1, 2, 3]).toHaveLength(3);
expect('abc').toHaveLength(3);
})
Copy the code
Note:
- There is no object determination here
.tobeInstanceof (Class) : Whether the matching instance is instantiated through the Class constructor
test('test toBeInstanceOf', () => {
class A { }
expect(new A()).toBeInstanceOf(A);
expect(() => { }).toBeInstanceOf(Function);
expect(new A()).toBeInstanceOf(Function); // throws
})
Copy the code
.toThrow(error?) /.toThrowError(error?) : Abnormal match
test('test toContainEqual', () => {
function throwFun() {
throw new Error('123abc')
}
expect(() => throwFun()).toThrow()
expect(() => throwFun()).toThrow('123')
expect(() => throwFun()).toThrow(/a/)
})
Copy the code
Note:
- Expect passes in a function to match the exception
.tohaveBeencalled ()/.tobecalled () : checks whether the function is alled
function callback(fn) { fn() } test('test toHaveBeenCalled', () => { const fn = jest.fn(); Callback (fn) expect(fn).tohaveBeencalled (); callback(fn) expect(fn).tohaveBeencalled (); expect(fn).toBeCalled(); })Copy the code
.toHaveBeenCalledWith(arg1, arg2, …) /.toBeCalledWith(arg1, arg2, …) : Checks whether the values passed by the calling function match
function callback(fn) {
fn(123)
}
test('test toHaveBeenCalledWith', () => {
const fn = jest.fn();
callback(fn)
expect(fn).toHaveBeenCalledWith(123);
expect(fn).toBeCalledWith(123);
expect(fn.mock.calls[0]).toEqual([123])
})
Copy the code
.toHaveBeenLastCalledWith(arg1, arg2, …) /.lastCalledWith(arg1, arg2, …) : Checks if the values passed in the last call to the function match
function callback(fn, arg) {
fn(arg)
}
test('test toHaveBeenLastCalledWith', () => {
const fn = jest.fn();
callback(fn, 123)
callback(fn, 456)
expect(fn).toHaveBeenLastCalledWith(456);
expect(fn).lastCalledWith(456);
})
Copy the code
.toHaveBeenNthCalledWith(nthCall, arg1, arg2, ….) /.nthCalledWith(nthCall, arg1, arg2, …) : Checks if the values passed in by the NTH function call match
function callback(fn, arg) {
fn(arg)
}
test('test toHaveBeenLastCalledWith', () => {
const fn = jest.fn();
callback(fn, 123)
callback(fn, 456)
callback(fn, 789)
expect(fn).toHaveBeenNthCalledWith(2, 456);
expect(fn).nthCalledWith(2, 456);
})
Copy the code
.tohaveBeencalledTimes (number)/.tobecalledTimes (number) : Checks whether the number of times the function is called matches
function callback(fn, arg) {
fn(arg)
}
test('test toHaveBeenCalledTimes', () => {
const fn = jest.fn();
callback(fn, 123)
callback(fn, 123)
callback(fn, 123)
expect(fn).toHaveBeenCalledTimes(3);
expect(fn).toBeCalledTimes(3);
})
Copy the code
.tohavereTurned ()/.toreturn () : Checks whether the function returns a value
test('test toHaveReturned', () => {
const fn = jest.fn(() => 123);
fn()
expect(fn).toHaveReturned();
expect(fn).toReturn();
})
Copy the code
.tohaveredTimes (number)/.toreturnTimes (number) : Checks the number of times the return value of the function is turnedtimes
test('test toHaveReturnedTimes', () => {
const fn = jest.fn(() => 123);
fn()
fn()
expect(fn).toHaveReturnedTimes(2);
expect(fn).toReturnTimes(2);
})
Copy the code
.tohaveredWith (value)/.toreturnWith (value) : Checks whether the return values of the function match
test('test toHaveReturnedWith', () => {
const fn = jest.fn(() => 123);
fn()
expect(fn).toHaveReturnedWith(123);
expect(fn).toReturnWith(123);
})
Copy the code
.tohavelastreturnedwith (value)/.lastredwith (value) : Checks whether the value returned by the last function matches
test('test toHaveLastReturnedWith', () => {
const fn = jest.fn((arg) => arg);
fn(123)
fn(456)
expect(fn).toHaveLastReturnedWith(456);
expect(fn).lastReturnedWith(456);
})
Copy the code
.tohaventhredwith (nthCall, value)/. Nthredwith (nthCall, value) : Checks whether the value returned by the NTH call of the function matches
test('test toHaveNthReturnedWith', () => {
const fn = jest.fn((arg) => arg);
fn(123)
fn(456)
expect(fn).toHaveNthReturnedWith(1, 123);
expect(fn).nthReturnedWith(2, 456);
})
Copy the code
So far, most of jest’s matchers have been covered, with a few less commonly used ones left unlisted. You’d better try it out for yourself to understand better. It’s a little hard to remember them all at once, but we just need to remember the ones we use commonly, and the rest we can use to query documents
My ability is limited, the article may have incorrect or inappropriate parts, I hope you can point out