-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
jest-expect.ts
401 lines (375 loc) · 12.2 KB
/
jest-expect.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
import type { EnhancedSpy } from '../jest-mock'
import type { ChaiPlugin } from './types'
import { arrayBufferEquality, equals as asymmetricEquals, hasAsymmetric, iterableEquality, sparseArrayEquality, typeEquality } from './jest-utils'
type MatcherState = {
assertionCalls: number
expectedAssertionsNumber: number | null
expectedAssertionsNumberError: Error | null
}
const MATCHERS_OBJECT = Symbol.for('matchers-object')
if (!Object.prototype.hasOwnProperty.call(global, MATCHERS_OBJECT)) {
const defaultState: Partial<MatcherState> = {
assertionCalls: 0,
expectedAssertionsNumber: null,
expectedAssertionsNumberError: null,
}
Object.defineProperty(global, MATCHERS_OBJECT, {
value: {
state: defaultState,
},
})
}
export const getState = <State extends MatcherState = MatcherState>(): State =>
(global as any)[MATCHERS_OBJECT].state
export const setState = <State extends MatcherState = MatcherState>(
state: Partial<State>,
): void => {
Object.assign((global as any)[MATCHERS_OBJECT].state, state)
}
// Jest Expect Compact
// TODO: add more https://jestjs.io/docs/expect
export const JestChaiExpect: ChaiPlugin = (chai, utils) => {
function def(name: keyof Chai.Assertion | (keyof Chai.Assertion)[], fn: ((this: Chai.AssertionStatic & Chai.Assertion, ...args: any[]) => any)) {
const addMethod = (n: keyof Chai.Assertion) => {
utils.addMethod(chai.Assertion.prototype, n, fn)
}
if (Array.isArray(name))
name.forEach(n => addMethod(n))
else
addMethod(name)
}
// we overrides the default `.equal`, keep original `.chaiEqual` in case need
// @ts-expect-error
const chaiEqual = chai.Assertion.prototype.equal
def('chaiEqual', function(...args: any[]) {
return chaiEqual.apply(this, args)
})
// overrides `.equal` and `.eql` to provide custom assertion for asymmetric equality
utils.overwriteMethod(chai.Assertion.prototype, 'equal', (_super: any) => {
return function(this: Chai.Assertion & Chai.AssertionStatic, ...args: any[]) {
const expected = args[0]
const actual = utils.flag(this, 'object')
// const negate = utils.flag(this, 'negate')
if (hasAsymmetric(expected)) {
this.assert(
asymmetricEquals(actual, expected, undefined, true),
'not match with #{act}',
'should not match with #{act}',
actual,
expected,
)
}
else {
_super.apply(this, args)
}
}
})
utils.overwriteMethod(chai.Assertion.prototype, 'eql', (_super: any) => {
return function(this: Chai.Assertion & Chai.AssertionStatic, ...args: any[]) {
const expected = args[0]
const actual = utils.flag(this, 'object')
if (hasAsymmetric(expected)) {
this.assert(
asymmetricEquals(actual, expected),
'not match with #{exp}',
'should not match with #{exp}',
expected,
actual,
)
}
else {
_super.apply(this, args)
}
}
})
def('toEqual', function(expected) {
return this.eql(expected)
})
def('toStrictEqual', function(expected) {
const obj = utils.flag(this, 'object')
const equal = asymmetricEquals(
obj,
expected,
[
iterableEquality,
typeEquality,
sparseArrayEquality,
arrayBufferEquality,
],
true,
)
return this.assert(
equal,
'expected #{this} to strictly equal #{exp}',
'expected #{this} to not strictly equal #{exp}',
expected,
obj,
)
})
def('toBe', function(expected) {
return this.equal(expected)
})
def('toMatchObject', function(expected) {
return this.containSubset(expected)
})
def('toMatch', function(expected: string | RegExp) {
if (typeof expected === 'string')
return this.include(expected)
else
return this.match(expected)
})
def('toContain', function(item) { return this.contain(item) })
def('toContainEqual', function(expected) {
const obj = utils.flag(this, 'object')
const index = Array.from(obj).findIndex((item) => {
try {
chai.assert.deepEqual(item, expected)
}
catch {
return false
}
return true
})
this.assert(
index !== -1,
'expected #{this} to deep equally contain #{exp}',
'expected #{this} to not deep equally contain #{exp}',
expected,
)
})
def('toBeTruthy', function() {
const obj = utils.flag(this, 'object')
this.assert(
Boolean(obj),
'expected #{this} to be truthy',
'expected #{this} to not be truthy',
obj,
)
})
def('toBeFalsy', function() {
const obj = utils.flag(this, 'object')
this.assert(
!obj,
'expected #{this} to be falsy',
'expected #{this} to not be falsy',
obj,
)
})
def('toBeGreaterThan', function(expected: number) {
return this.to.greaterThan(expected)
})
def('toBeGreaterThanOrEqual', function(expected: number) {
return this.to.greaterThanOrEqual(expected)
})
def('toBeLessThan', function(expected: number) {
return this.to.lessThan(expected)
})
def('toBeLessThanOrEqual', function(expected: number) {
return this.to.lessThanOrEqual(expected)
})
def('toBeNaN', function() {
return this.be.NaN
})
def('toBeUndefined', function() {
return this.be.undefined
})
def('toBeNull', function() {
return this.be.null
})
def('toBeDefined', function() {
return this.not.be.undefined
})
def('toBeInstanceOf', function(obj: any) {
return this.instanceOf(obj)
})
def('toHaveLength', function(length: number) {
return this.have.length(length)
})
// destructuring, because it checks `arguments` inside, and value is passing as `undefined`
def('toHaveProperty', function(...args: [property: string, value?: any]) {
return this.have.deep.nested.property(...args)
})
def('toBeCloseTo', function(number: number, numDigits = 2) {
utils.expectTypes(this, ['number'])
return this.closeTo(number, numDigits)
})
// mock
function isSpy(putativeSpy: any) {
return typeof putativeSpy === 'function'
&& '__isSpy' in putativeSpy
&& putativeSpy.__isSpy
}
const assertIsMock = (assertion: any) => {
if (!isSpy(assertion._obj))
throw new TypeError(`${utils.inspect(assertion._obj)} is not a spy or a call to a spy!`)
}
const getSpy = (assertion: any) => {
assertIsMock(assertion)
return assertion._obj as EnhancedSpy
}
def(['toHaveBeenCalledTimes', 'toBeCalledTimes'], function(number: number) {
const spy = getSpy(this)
const spyName = spy.getMockName()
return this.assert(
spy.callCount === number,
`expected "${spyName}" to be called #{exp} times`,
`expected "${spyName}" to not be called #{exp} times`,
number,
spy.callCount,
)
})
def('toHaveBeenCalledOnce', function() {
const spy = getSpy(this)
const spyName = spy.getMockName()
return this.assert(
spy.callCount === 1,
`expected "${spyName}" to be called once`,
`expected "${spyName}" to not be called once`,
1,
spy.callCount,
)
})
def(['toHaveBeenCalled', 'toBeCalled'], function() {
const spy = getSpy(this)
const spyName = spy.getMockName()
return this.assert(
spy.called,
`expected "${spyName}" to be called at least once`,
`expected "${spyName}" to not be called at all`,
true,
spy.called,
)
})
def(['toHaveBeenCalledWith', 'toBeCalledWith'], function(...args) {
const spy = getSpy(this)
const spyName = spy.getMockName()
const pass = spy.calls.some(callArg => asymmetricEquals(callArg, args))
return this.assert(
pass,
`expected "${spyName}" to be called with arguments: #{exp}`,
`expected "${spyName}" to not be called with arguments: #{exp}`,
args,
spy.calls,
)
})
const ordinalOf = (i: number) => {
const j = i % 10
const k = i % 100
if (j === 1 && k !== 11)
return `${i}st`
if (j === 2 && k !== 12)
return `${i}nd`
if (j === 3 && k !== 13)
return `${i}rd`
return `${i}th`
}
def(['toHaveBeenNthCalledWith', 'nthCalledWith'], function(times: number, ...args: any[]) {
const spy = getSpy(this)
const spyName = spy.getMockName()
const nthCall = spy.calls[times - 1]
this.assert(
asymmetricEquals(nthCall, args),
`expected ${ordinalOf(times)} "${spyName}" call to have been called with #{exp}`,
`expected ${ordinalOf(times)} "${spyName}" call to not have been called with #{exp}`,
args,
nthCall,
)
})
def(['toHaveBeenLastCalledWith', 'lastCalledWith'], function(...args: any[]) {
const spy = getSpy(this)
const spyName = spy.getMockName()
const lastCall = spy.calls[spy.calls.length - 1]
this.assert(
asymmetricEquals(lastCall, args),
`expected last "${spyName}" call to have been called with #{exp}`,
`expected last "${spyName}" call to not have been called with #{exp}`,
args,
lastCall,
)
})
def(['toThrow', 'toThrowError'], function(expected: string | RegExp) {
const negate = utils.flag(this, 'negate')
if (negate)
this.not.to.throw(expected)
else
this.to.throw(expected)
})
def(['toHaveReturned', 'toReturn'], function() {
const spy = getSpy(this)
const spyName = spy.getMockName()
const calledAndNotThrew = spy.called && !spy.results.some(([type]) => type === 'error')
this.assert(
calledAndNotThrew,
`expected "${spyName}" to be successfully called at least once`,
`expected "${spyName}" to not be successfully called`,
calledAndNotThrew,
!calledAndNotThrew,
)
})
def(['toHaveReturnedTimes', 'toReturnTimes'], function(times: number) {
const spy = getSpy(this)
const spyName = spy.getMockName()
const successfullReturns = spy.results.reduce((success, [type]) => type === 'error' ? success : ++success, 0)
this.assert(
successfullReturns === times,
`expected "${spyName}" to be successfully called ${times} times`,
`expected "${spyName}" to not be successfully called ${times} times`,
`expected number of returns: ${times}`,
`received number of returns: ${successfullReturns}`,
)
})
def(['toHaveReturnedWith', 'toReturnWith'], function(value: any) {
const spy = getSpy(this)
const spyName = spy.getMockName()
const pass = spy.results.some(([type, result]) => type === 'ok' && asymmetricEquals(value, result))
this.assert(
pass,
`expected "${spyName}" to be successfully called with #{exp}`,
`expected "${spyName}" to not be successfully called with #{exp}`,
value,
)
})
def(['toHaveLastReturnedWith', 'lastReturnedWith'], function(value: any) {
const spy = getSpy(this)
const spyName = spy.getMockName()
const lastResult = spy.returns[spy.returns.length - 1]
const pass = asymmetricEquals(lastResult, value)
this.assert(
pass,
`expected last "${spyName}" call to return #{exp}`,
`expected last "${spyName}" call to not return #{exp}`,
value,
lastResult,
)
})
def(['toHaveNthReturnedWith', 'nthReturnedWith'], function(nthCall: number, value: any) {
const spy = getSpy(this)
const spyName = spy.getMockName()
const isNot = utils.flag(this, 'negate') as boolean
const [callType, callResult] = spy.results[nthCall - 1]
const ordinalCall = `${ordinalOf(nthCall)} call`
if (!isNot && callType === 'error')
chai.assert.fail(`expected ${ordinalCall} to return #{exp}, but instead it threw an error`)
const nthCallReturn = asymmetricEquals(callResult, value)
this.assert(
nthCallReturn,
`expected ${ordinalCall} "${spyName}" call to return #{exp}`,
`expected ${ordinalCall} "${spyName}" call to not return #{exp}`,
value,
callResult,
)
})
utils.addMethod(
chai.expect,
'assertions',
function assertions(expected: number) {
const error = new Error(`expected number of assertions to be ${expected}, but got ${getState().assertionCalls}`)
if (Error.captureStackTrace)
Error.captureStackTrace(error, assertions)
setState({
expectedAssertionsNumber: expected,
expectedAssertionsNumberError: error,
})
},
)
}