- Clone repo:
git clone https://naftalimurgor.com/unit-testing-with-jest
- Install dependencies:
npm install
- Run the test:
npm test
- Add more tests and tinker around with various custom matchers:
/* Custom matchers provided by jest-extended */
// .pass(message)
// .fail(message)
// .toBeEmpty()
// .toBeOneOf([members])
// .toBeNil()
// .toSatisfy(predicate)
// Array
// .toBeArray()
// .toBeArrayOfSize()
// .toIncludeAllMembers([members])
// .toIncludeAllPartialMembers([members])
// .toIncludeAnyMembers([members])
// .toIncludeSameMembers([members])
// .toPartiallyContain(member)
// .toSatisfyAll(predicate)
// .toSatisfyAny(predicate)
// Boolean
// .toBeBoolean()
// .toBeTrue()
// .toBeFalse()
// Date
// .toBeDate()
// .toBeValidDate()
// .toBeAfter(date)
// .toBeBefore(date)
// .toBeAfterOrEqualTo(date)
// .toBeBeforeOrEqualTo(date)
// .toBeBetween(startDate, endDate)
// Further proposals in #117 PRs welcome
// Function
// .toBeFunction()
// .toThrowWithMessage()
// Mock
// .toHaveBeenCalledBefore()
// .toHaveBeenCalledAfter()
// .toHaveBeenCalledOnce()
// Number
// .toBeNumber()
// .toBeNaN()
// .toBeFinite()
// .toBePositive()
// .toBeNegative()
// .toBeEven()
// .toBeOdd()
// .toBeWithin(start, end)
// .toBeInteger()
// Object
// .toBeObject()
// .toBeEmptyObject()
// .toContainKey(key)
// .toContainKeys([keys])
// .toContainAllKeys([keys])
// .toContainAnyKeys([keys])
// .toContainValue(value)
// .toContainValues([values])
// .toContainAllValues([values])
// .toContainAnyValues([values])
// .toContainEntry([key, value])
// .toContainEntries([[key, value]])
// .toContainAllEntries([[key, value]])
// .toContainAnyEntries([[key, value]])
// .toBeExtensible()
// .toBeFrozen()
// .toBeSealed()
// Promise
// .toResolve()
// .toReject()
// String
// .toBeString()
// .toBeHexadecimal(string)
// .toBeDateString(string)
// .toEqualCaseInsensitive(string)
// .toStartWith(prefix)
// .toEndWith(suffix)
// .toInclude(substring)
// .toIncludeRepeated(substring, times)
// .toIncludeMultiple([substring])
// .toEqualIgnoringWhitespace(string)
- Generating
jest.config.ts
file, handles project widejest
custom configuration - Using custom matchers provided by jest-extended
- Default matchers provided by jest using matchers
- Testing asynchronous code -
async/await
const config: Config.InitialOptions = {
// ts-jest
preset: 'ts-jest',
testEnvironment: 'node',
verbose: true,
automock: false,
clearMocks: true,
collectCoverage: true,
// https://github.com/jest-community/jest-extended: Extended matchers
setupFilesAfterEnv: ['jest-extended/all'],
}
{
...
"scripts:" {
"clear_jest": "jest --clearCache"
}
...
}
## or simply run:
jest --clearCache
Add a global.d.ts file in the project root, and add the following import:
import 'jest-extended'