|
| 1 | +import type { MatcherFunction } from 'expect'; |
| 2 | +import { Address, Cell, Slice } from '@ton/core'; |
| 3 | + |
| 4 | +import { FlatTransactionComparable, compareTransactionForTest } from './transaction'; |
| 5 | +import { CompareResult } from './interface'; |
| 6 | +import { compareAddressForTest, compareCellForTest, compareSliceForTest } from './comparisons'; |
| 7 | +import { compareThrownExitCodeForTest } from './exitCode'; |
| 8 | + |
| 9 | +function extractResult(result: CompareResult) { |
| 10 | + return { |
| 11 | + pass: result.pass, |
| 12 | + message: () => { |
| 13 | + if (result.pass) { |
| 14 | + return result.negMessage(); |
| 15 | + } else { |
| 16 | + return result.posMessage(); |
| 17 | + } |
| 18 | + }, |
| 19 | + }; |
| 20 | +} |
| 21 | + |
| 22 | +function wrapComparer<T>( |
| 23 | + comparer: (subject: unknown, cmp: T) => CompareResult | Promise<CompareResult>, |
| 24 | +): MatcherFunction<[cmp: T]> { |
| 25 | + return function (actual, cmp) { |
| 26 | + const result = comparer(actual, cmp); |
| 27 | + if (result instanceof Promise) { |
| 28 | + return result.then(extractResult); |
| 29 | + } |
| 30 | + return extractResult(result); |
| 31 | + }; |
| 32 | +} |
| 33 | + |
| 34 | +const toHaveTransaction = wrapComparer(compareTransactionForTest); |
| 35 | +const toEqualCell = wrapComparer(compareCellForTest); |
| 36 | +const toEqualAddress = wrapComparer(compareAddressForTest); |
| 37 | +const toEqualSlice = wrapComparer(compareSliceForTest); |
| 38 | +const toThrowExitCode = wrapComparer(compareThrownExitCodeForTest); |
| 39 | + |
| 40 | +try { |
| 41 | + // eslint-disable-next-line @typescript-eslint/no-require-imports |
| 42 | + const bunTest = require('bun:test'); |
| 43 | + |
| 44 | + if (bunTest && bunTest.expect) |
| 45 | + bunTest.expect.extend({ |
| 46 | + toHaveTransaction, |
| 47 | + toEqualCell, |
| 48 | + toEqualAddress, |
| 49 | + toEqualSlice, |
| 50 | + toThrowExitCode, |
| 51 | + }); |
| 52 | + // eslint-disable-next-line no-empty |
| 53 | +} catch (_) {} |
| 54 | + |
| 55 | +interface TonMatchers<T> { |
| 56 | + toHaveTransaction(cmp: FlatTransactionComparable): T; |
| 57 | + toEqualCell(cell: Cell): T; |
| 58 | + toEqualAddress(address: Address): T; |
| 59 | + toEqualSlice(slice: Slice): T; |
| 60 | + |
| 61 | + /** |
| 62 | + * @example |
| 63 | + * await expect(() => blockchain.runGetMethod(contract.address, 'test')).toThrowExitCode(11); |
| 64 | + */ |
| 65 | + toThrowExitCode(exitCode: number): Promise<T>; |
| 66 | +} |
| 67 | + |
| 68 | +declare module 'bun:test' { |
| 69 | + // eslint-disable-next-line @typescript-eslint/no-empty-object-type |
| 70 | + interface Matchers<T> extends TonMatchers<T> {} |
| 71 | +} |
0 commit comments