forked from vitest-dev/vitest
/
index.ts
76 lines (63 loc) · 2.36 KB
/
index.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
import * as chai from 'chai'
import './setup'
import type { Test } from '../../types'
import { getCurrentEnvironment, getFullName } from '../../utils'
import type { MatcherState } from '../../types/chai'
import { getState, setState } from './jest-expect'
import { GLOBAL_EXPECT } from './constants'
export function createExpect(test?: Test) {
const expect = ((value: any, message?: string): Vi.Assertion => {
const { assertionCalls } = getState(expect)
setState({ assertionCalls: assertionCalls + 1 }, expect)
const assert = chai.expect(value, message) as unknown as Vi.Assertion
if (test)
// @ts-expect-error internal
return assert.withTest(test) as Vi.Assertion
else
return assert
}) as Vi.ExpectStatic
Object.assign(expect, chai.expect)
expect.getState = () => getState(expect)
expect.setState = state => setState(state as Partial<MatcherState>, expect)
setState({
assertionCalls: 0,
isExpectingAssertions: false,
isExpectingAssertionsError: null,
expectedAssertionsNumber: null,
expectedAssertionsNumberErrorGen: null,
environment: getCurrentEnvironment(),
testPath: test?.suite.file?.filepath,
currentTestName: test ? getFullName(test) : undefined,
}, expect)
// @ts-expect-error untyped
expect.extend = matchers => chai.expect.extend(expect, matchers)
function assertions(expected: number) {
const errorGen = () => new Error(`expected number of assertions to be ${expected}, but got ${expect.getState().assertionCalls}`)
if (Error.captureStackTrace)
Error.captureStackTrace(errorGen(), assertions)
expect.setState({
expectedAssertionsNumber: expected,
expectedAssertionsNumberErrorGen: errorGen,
})
}
function hasAssertions() {
const error = new Error('expected any number of assertion, but got none')
if (Error.captureStackTrace)
Error.captureStackTrace(error, hasAssertions)
expect.setState({
isExpectingAssertions: true,
isExpectingAssertionsError: error,
})
}
chai.util.addMethod(expect, 'assertions', assertions)
chai.util.addMethod(expect, 'hasAssertions', hasAssertions)
return expect
}
const globalExpect = createExpect()
Object.defineProperty(globalThis, GLOBAL_EXPECT, {
value: globalExpect,
writable: true,
configurable: true,
})
export { assert, should } from 'chai'
export { chai, globalExpect as expect }