预计
当你写测试,你经常需要检查值满足一定的条件。 expect 让您可以访问一些“匹配器”,让您验证不同的东西。
For additional Jest matchers maintained by the Jest Community check out jest-extended.
方法
-
expect(value)
-
expect.extend(matchers)
-
expect.anything()
-
expect.any(constructor)
-
expect.arrayContaining(array)
-
expect.assertions(number)
-
expect.hasAssertions()
-
expect.not.arrayContaining(array)
-
expect.not.objectContaining(object)
-
expect.not.stringContaining(string)
-
expect.not.stringMatching(string | regexp)
-
expect.objectContaining(object)
-
expect.stringContaining(string)
-
expect.stringMatching(string | regexp)
-
expect.addSnapshotSerializer(serializer)
-
.not
-
.resolves
-
.rejects
-
.toBe(value)
-
.toHaveBeenCalled()
-
.toHaveBeenCalledTimes(number)
-
.toHaveBeenCalledWith(arg1, arg2, ...)
-
.toHaveBeenLastCalledWith(arg1, arg2, ...)
-
.toHaveBeenNthCalledWith(nthCall, arg1, arg2, ....)
-
.toHaveReturned()
-
.toHaveReturnedTimes(number)
-
.toHaveReturnedWith(value)
-
.toHaveLastReturnedWith(value)
-
.toHaveNthReturnedWith(nthCall, value)
-
.toHaveLength(number)
-
.toHaveProperty(keyPath, value?)
-
.toBeCloseTo(number, numDigits?)
-
.toBeDefined()
-
.toBeFalsy()
-
.toBeGreaterThan(number | bigint)
-
.toBeGreaterThanOrEqual(number | bigint)
-
.toBeLessThan(number | bigint)
-
.toBeLessThanOrEqual(number | bigint)
-
.toBeInstanceOf(Class)
-
.toBeNull()
-
.toBeTruthy()
-
.toBeUndefined()
-
.toBeNaN()
-
.toContain(item)
-
.toContainEqual(item)
-
.toEqual(value)
-
.toMatch(regexp | string)
-
.toMatchObject(object)
-
.toMatchSnapshot(propertyMatchers?, hint?)
-
.toMatchInlineSnapshot(propertyMatchers?, inlineSnapshot)
-
.toStrictEqual(value)
-
.toThrow(error?)
-
.toThrowErrorMatchingSnapshot(hint?)
-
.toThrowErrorMatchingInlineSnapshot(inlineSnapshot)
Reference
expect(value)
每次要测试一个值时都会使用expect函数。 你很少会自己调用expect。 相反,您将使用expect及 “matcher” 函数来断言某个值。
很容易理解这一点的一个例子。 假设你有一个方法bestLaCroixFlavor(),它应该返回字符串'grapefruit'。 以下是您如何测试:
test('the best flavor is grapefruit', () => { expect(bestLaCroixFlavor()).toBe('grapefruit');});
在这种情况下,toBe是匹配器函数。 有很多不同的匹配器函数,如下所述,可帮助您测试不同的内容。
expect的参数应该是您的代码产生的值,匹配器的任何参数应该是正确的值。 如果您混合使用,您的测试仍然可以工作,但是失败测试的错误信息将会显得奇怪。
expect.extend(matchers)
您可以使用expect.extend将自己的匹配器添加到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: You could abstract that into a toBeWithinRange matcher:
expect.extend({ toBeWithinRange(received, floor, ceiling) { const pass = received >= floor && received <= ceiling; if (pass) { return { message: () => `expected ${received} not to be within range ${floor} - ${ceiling}`, pass: true, }; } else { return { message: () => `expected ${received} to be within range ${floor} - ${ceiling}`, pass: false, }; } },});test('numeric ranges', () => { expect(100).toBeWithinRange(90, 110); expect(101).not.toBeWithinRange(0, 100); expect({apples: 6, bananas: 3}).toEqual({ apples: expect.toBeWithinRange(1, 10), bananas: expect.not.toBeWithinRange(11, 20), });});
Note: In TypeScript, when using @types/jest for example, you can declare the new toBeWithinRange matcher in the imported module like this:
declare global { namespace jest { interface Matchers<R> { toBeWithinRange(a: number, b: number): R; } }}
Async Matchers
expect.extend also supports async matchers. Async matchers return a Promise so you will need to await the returned value. Let’s use an example matcher to illustrate the usage of them. We are going to implement a matcher called toBeDivisibleByExternalValue, where the divisible number is going to be pulled from an external source.
expect.extend({ async toBeDivisibleByExternalValue(received) { const externalValue = await getExternalValueFromRemoteSource(); const pass = received % externalValue == 0; if (pass) { return { message: () => `expected ${received} not to be divisible by ${externalValue}`, pass: true, }; } else { return { message: () => `expected ${received} to be divisible by ${externalValue}`, pass: false, }; } },});test('is divisible by external value', async () => { await expect(100).toBeDivisibleByExternalValue(); await expect(101).not.toBeDivisibleByExternalValue();});
Custom Matchers API
Matchers should return an object (or a Promise of an object) with two keys. Matchers should return an object (or a Promise of an object) with two keys. pass表示是否有匹配,而message 提供了一个没有参数的函数,在出现故障的情况下返回错误消息。 因此,当pass为false时,message应该返回当expect(x).yourMatcher()失败时的错误消息。 而当pass为true时, message应该返回当expect(x).not.yourMatcher()失败时的错误信息。
Matchers are called with the argument passed to expect(x) followed by the arguments passed to .yourMatcher(y, z):
expect.extend({ yourMatcher(x, y, z) { return { pass: true, message: () => '', }; },});
These helper functions and properties 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 display a clear and correct matcher hint (see example code).
this.promise
A string allowing you to display a clear and correct matcher hint:
-
'rejects' if matcher was called with the promise .rejects modifier
-
'resolves' if matcher was called with the promise .resolves modifier
-
'' if matcher was not called with a promise modifier
this.equals(a, b)
A boolean to let you know this matcher was called with an expand option. When Jest is called with the --expand flag, this.expand can be used to determine if Jest is expected to show full diffs and errors.
this.expand
A boolean to let you know this matcher was called with an expand option. When Jest is called with the --expand flag, this.expand can be used to determine if Jest is expected to show full diffs and errors.
this.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:
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 options = { comment: 'Object.is equality', isNot: this.isNot, promise: this.promise, }; const pass = Object.is(received, expected); const message = pass ? () => this.utils.matcherHint('toBe', undefined, undefined, options) + '\n\n' + `Expected: not ${this.utils.printExpected(expected)}\n` + `Received: ${this.utils.printReceived(received)}` : () => { const diffString = diff(expected, received, { expand: this.expand, }); return ( this.utils.matcherHint('toBe', undefined, undefined, options) + '\n\n' + (diffString && diffString.includes('- Expect') ? `Difference:\n\n${diffString}` : `Expected: ${this.utils.printExpected(expected)}\n` + `Received: ${this.utils.printReceived(received)}`) ); }; return {actual: received, message, pass}; },});
This will print something like this:
expect(received).toBe(expected) Expected value to be (using Object.is): "banana" Received: "apple"
