@orieljs/testing 0.1.0-alpha.5 → 0.1.0-alpha.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/NOTICE CHANGED
@@ -7,3 +7,10 @@ This product includes software developed by the Oriel project
7
7
  Oriel is licensed under the Apache License, Version 2.0 (see LICENSE).
8
8
  The Oriel name and logo are not covered by that license; see TRADEMARKS.md
9
9
  (https://github.com/orieljs/framework/blob/main/TRADEMARKS.md).
10
+
11
+ @orieljs/support (and @orieljs/framework, which bundles it) includes transliteration data from
12
+ voku/portable-ascii (https://github.com/voku/portable-ascii), Copyright (C) 2019 Lars Moelleken, MIT License.
13
+
14
+ @orieljs/notifications (and @orieljs/framework, which bundles it) includes the HTML and CSS of
15
+ Laravel's default notification mail (laravel/framework, https://github.com/laravel/framework),
16
+ Copyright (c) Taylor Otwell, MIT License.
package/README.md ADDED
@@ -0,0 +1,44 @@
1
+ # @orieljs/testing
2
+
3
+ Testing for Oriel: a fresh application for every test, HTTP requests against it, database helpers and fakes, as Laravel's testing helpers. Tests run on Vitest. In an app, import it from `@orieljs/framework/testing`; `@orieljs/testing` is also published on its own.
4
+
5
+ ```bash
6
+ npm install @orieljs/framework
7
+ npm install -D vitest
8
+ ```
9
+
10
+ ```ts title="tests/Feature/Podcast.test.ts"
11
+ // @filename: tests/TestCase.ts
12
+ import { TestCase as BaseTestCase } from '@orieljs/framework/testing'
13
+ import { afterEach, beforeEach } from 'vitest'
14
+ export class TestCase extends BaseTestCase { static override hooks = { beforeEach, afterEach } }
15
+ // ---cut---
16
+ import { Queue } from '@orieljs/framework'
17
+ import { RefreshDatabase } from '@orieljs/framework/testing'
18
+ import { test } from 'vitest'
19
+ import { ProcessPodcast } from '../../app/Jobs/ProcessPodcast'
20
+ import { User } from '../../app/Models/User'
21
+ import { TestCase } from '../TestCase'
22
+
23
+ const t = TestCase.boot({ uses: [RefreshDatabase] })
24
+
25
+ test('creating a podcast queues its processing', async () => {
26
+ const queue = Queue.fake()
27
+ const user = await User.create({ name: 'Ada', email: 'ada@example.com', password: 'secret' })
28
+
29
+ ;(await t.actingAs(user).post('/podcasts', { title: 'Episode 1' })).assertRedirect('/podcasts')
30
+ queue.assertPushed(ProcessPodcast)
31
+ })
32
+ ```
33
+
34
+ An app's tests extend `tests/TestCase.ts`: `TestCase.boot()` gives each test a new application, and `RefreshDatabase` gives it a migrated database and undoes its changes. `t.get()`, `t.post()` and the other request methods resolve to a `TestResponse`, with assertions such as `assertOk()`, `assertRedirect()`, `assertJson()` and `assertInertia()`. Imported from `@orieljs/framework`, `Mail.fake()`, `Queue.fake()`, `Bus.fake()`, `Event.fake()`, `Notification.fake()` and `Storage.fake()` swap the real services for fakes that record what the app does.
35
+
36
+ Documentation: https://orieljs.vercel.app/docs/testing
37
+
38
+ Status: early alpha. APIs will change.
39
+
40
+ ## License
41
+
42
+ Oriel is open-source software licensed under the Apache License 2.0 (Apache-2.0; see `LICENSE` and `NOTICE`). The Oriel name and logo are trademarks; see `TRADEMARKS.md`.
43
+
44
+ Website: https://orieljs.vercel.app
package/TRADEMARKS.md ADDED
@@ -0,0 +1,33 @@
1
+ # Oriel trademark policy
2
+
3
+ The Oriel code is open source under the Apache License 2.0. The **Oriel name and logo** are not: the license covers
4
+ the code only (section 6 of the license says so), and the name and logo stay with the project. This page explains
5
+ what you can and can't do with them. The goal is simple: people should always be able to tell what is the real Oriel
6
+ and what isn't.
7
+
8
+ ## You can, without asking
9
+
10
+ - Use, change, ship and sell the code, as the license allows.
11
+ - Say that your app or package is "built with Oriel", "for Oriel" or "compatible with Oriel".
12
+ - Name a package `oriel-<something>` or `<something>-for-oriel` when it works with Oriel, as long as it is clear that
13
+ it is not official (for example, don't publish it under the `@orieljs` npm scope).
14
+ - Use the name and logo to write about Oriel, teach it, or link to it, in articles, talks, videos and courses.
15
+ - Use the unmodified logo to point to the project, as it is (no recolouring, cropping or
16
+ distortion).
17
+
18
+ ## You can't, without written permission
19
+
20
+ - Call a fork, a modified copy or a competing product "Oriel", or anything likely to be confused with it.
21
+ - Use the name or logo as the name, logo or domain of your own product, company or service.
22
+ - Suggest that the Oriel project made, endorses or supports your work when it doesn't.
23
+ - Sell merchandise with the name or logo.
24
+
25
+ ## Forks
26
+
27
+ Forks are welcome. Please give yours a different name and logo, keep the `LICENSE` and `NOTICE` files, and say that
28
+ it is based on Oriel.
29
+
30
+ ## Questions
31
+
32
+ Open an issue at https://github.com/orieljs/framework or email meeeet.dev@gmail.com. If you're unsure whether a use
33
+ is fine, ask; the answer is usually yes.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,68 @@
1
1
  import { Application, ModelInstance, InertiaPage, Encrypter, Session, View, Authenticatable, Container, AuthFactory, ServiceProvider, ServiceProviderClass, DatabaseManager, Row, ExceptionHandler, ViewFactory, Class, Token, EventDispatcher, Listener, PendingBatchOptions, Job, BusDispatcher, PendingChain, PendingBatch, Batch, QueuePayload, QueueManager, Queue, QueueJob, MailManager, Mailable, Address, MailRecipient, Mailer, PendingMail, SentMessage, MailTransport, Notifiable, NotificationDispatcher, Notification, NotificationChannel, Filesystem, PutOptions, UploadedFile, FilesystemManager } from '@orieljs/contracts';
2
2
 
3
+ /** A date the tests travel to: a Date, an ISO string or milliseconds since the epoch. */
4
+ type TravelDate = Date | string | number;
5
+ /**
6
+ * Laravel's travelTo(): the clock stands at `date` (new Date(), Date.now() and now() all read it) until travelBack().
7
+ * With a callback, it runs there and the clock travels back after it; its result is returned.
8
+ */
9
+ declare function travelTo(date: TravelDate): void;
10
+ declare function travelTo<R>(date: TravelDate, callback: (date: Date) => R): R;
11
+ /** Laravel's travelBack(): the real clock again. Returns the real time. */
12
+ declare function travelBack(): Date;
13
+ /** Laravel's freezeTime(): holds the clock where it is now. Returns that time, or the callback's result. */
14
+ declare function freezeTime(): Date;
15
+ declare function freezeTime<R>(callback: (date: Date) => R): R;
16
+ /** Laravel's freezeSecond(): freezeTime() at the start of the current second. */
17
+ declare function freezeSecond(): Date;
18
+ declare function freezeSecond<R>(callback: (date: Date) => R): R;
19
+ /** Laravel's travel(5).minutes(): moves the clock on (a negative value moves it back) from where it stands. */
20
+ declare function travel(value: number): Wormhole;
21
+ /**
22
+ * Laravel's Wormhole: each unit moves the clock by `value` of it (months and years overflow as Carbon's do: 31 January
23
+ * plus a month is 3 March), in UTC. With a callback, it runs there, the clock travels back after it, and its result is
24
+ * returned. JavaScript dates hold milliseconds, so there are no microseconds.
25
+ */
26
+ declare class Wormhole {
27
+ #private;
28
+ readonly value: number;
29
+ constructor(value: number);
30
+ millisecond(): void;
31
+ millisecond<R>(callback: () => R): R;
32
+ milliseconds(): void;
33
+ milliseconds<R>(callback: () => R): R;
34
+ second(): void;
35
+ second<R>(callback: () => R): R;
36
+ seconds(): void;
37
+ seconds<R>(callback: () => R): R;
38
+ minute(): void;
39
+ minute<R>(callback: () => R): R;
40
+ minutes(): void;
41
+ minutes<R>(callback: () => R): R;
42
+ hour(): void;
43
+ hour<R>(callback: () => R): R;
44
+ hours(): void;
45
+ hours<R>(callback: () => R): R;
46
+ day(): void;
47
+ day<R>(callback: () => R): R;
48
+ days(): void;
49
+ days<R>(callback: () => R): R;
50
+ week(): void;
51
+ week<R>(callback: () => R): R;
52
+ weeks(): void;
53
+ weeks<R>(callback: () => R): R;
54
+ month(): void;
55
+ month<R>(callback: () => R): R;
56
+ months(): void;
57
+ months<R>(callback: () => R): R;
58
+ year(): void;
59
+ year<R>(callback: () => R): R;
60
+ years(): void;
61
+ years<R>(callback: () => R): R;
62
+ /** Laravel's Wormhole::back(). */
63
+ static back(): Date;
64
+ }
65
+
3
66
  /**
4
67
  * Laravel's PendingCommand: `await t.artisan('inspire').expectsOutput('…').assertExitCode(0)`.
5
68
  * It runs through ConsoleKernel.call() when awaited (or run()), then checks every expectation against the
@@ -354,6 +417,11 @@ declare class HttpClient {
354
417
  defaultGuard: string | undefined;
355
418
  /** Session attributes carried from one request to the next (Laravel keeps one session store per test). */
356
419
  session: Record<string, unknown> | undefined;
420
+ /**
421
+ * withSession() and flushSession() since the last started session: applied to the stored session (the one the
422
+ * session cookie points to) once the next request starts it, so they win over what it holds, as in Laravel.
423
+ */
424
+ sessionChanges: Array<(session: Session) => void>;
357
425
  /** from(url): the session's previous URL for the next request only (Laravel sets it once). */
358
426
  previousUrl: string | undefined;
359
427
  /** Requests whose actingAs users reached the guards (the AuthFactory they went through). */
@@ -379,6 +447,10 @@ declare class HttpClient {
379
447
  * request sticks. Reads each actingAs guard back and forgets or replaces its user to match.
380
448
  */
381
449
  protected syncActingAs(auth: AuthFactory): Promise<void>;
450
+ /** Applies the pending withSession()/flushSession() changes once the session has loaded what it stored. */
451
+ protected applyOnStart(session: Session): void;
452
+ /** Applies the pending withSession()/flushSession() changes to the session, once. */
453
+ protected applyPending(session: Session): void;
382
454
  /** The request's (scoped) Session, created now so the carried attributes are in place before StartSession. */
383
455
  protected scopeSession(scope: Container): Session | undefined;
384
456
  buildRequest(method: string, uri: string, options: RequestOptions): Request;
@@ -475,9 +547,9 @@ declare abstract class MakesHttpRequests extends InteractsWithApplication {
475
547
  followingRedirects(): this;
476
548
  /** Sets the Referer and the session's previous URL, so redirect()->back() goes there. */
477
549
  from(url: string): this;
478
- /** Puts data in the session for the following requests (Laravel's withSession()). */
550
+ /** Puts data in the session for the following requests, over what the stored session holds (Laravel's withSession()). */
479
551
  withSession(data: Record<string, unknown>): this;
480
- /** Empties the session carried between requests. */
552
+ /** Empties the session, the stored one included, so the next request starts with none (Laravel's flushSession()). */
481
553
  flushSession(): this;
482
554
  /** Every following request is authenticated as `user` on `guard` (which also becomes the default guard). */
483
555
  actingAs(user: Authenticatable, guard?: string): this;
@@ -536,11 +608,28 @@ declare abstract class InteractsWithConsole extends InteractsWithDatabase {
536
608
  artisan(command: string, parameters?: Record<string, unknown>): PendingCommand;
537
609
  }
538
610
 
611
+ /**
612
+ * Laravel's InteractsWithTime: `t.travelTo(date)`, `t.travel(5).minutes()`, `t.freezeTime()`, `t.travelBack()`.
613
+ * The functions of the same names do the same outside a test case. A test case's tearDown travels back, so each of its
614
+ * tests ends in the real time; with the plain functions, call `travelBack()` in your own `afterEach()` or pass a callback.
615
+ */
616
+ declare abstract class InteractsWithTime extends InteractsWithConsole {
617
+ travelTo(date: TravelDate): void;
618
+ travelTo<R>(date: TravelDate, callback: (date: Date) => R): R;
619
+ travel(value: number): Wormhole;
620
+ travelBack(): Date;
621
+ freezeTime(): Date;
622
+ freezeTime<R>(callback: (date: Date) => R): R;
623
+ freezeSecond(): Date;
624
+ freezeSecond<R>(callback: (date: Date) => R): R;
625
+ tearDown(): Promise<void>;
626
+ }
627
+
539
628
  /**
540
629
  * Laravel's TestCase. Extend it in tests/TestCase.ts (override createApplication() and set `static hooks`),
541
630
  * then in each file: `const t = TestCase.boot()`, or `TestCase.boot({ uses: [RefreshDatabase] })`.
542
631
  */
543
- declare abstract class TestCase extends InteractsWithConsole {
632
+ declare abstract class TestCase extends InteractsWithTime {
544
633
  }
545
634
 
546
635
  /**
@@ -619,6 +708,8 @@ interface DispatchedEvent {
619
708
  payload: unknown[];
620
709
  }
621
710
  type EventFilter<E> = (event: E, payload: unknown[]) => boolean;
711
+ /** A listener as assertListening() expects it: a class, a [class, method] pair, a closure, or Function for any closure. */
712
+ type ExpectedListener = Listener<never> | readonly [Class<object>, string] | FunctionConstructor;
622
713
  /**
623
714
  * Laravel's Event::fake(): records dispatched events instead of running listeners. With a list, only those
624
715
  * events are faked and everything else reaches the original dispatcher (so model events keep working).
@@ -649,11 +740,17 @@ declare class EventFake implements EventDispatcher {
649
740
  assertDispatchedTimes<E>(event: Class<E> | string, times?: number): void;
650
741
  assertNotDispatched<E>(event: Class<E> | string, callback?: EventFilter<E>): void;
651
742
  assertNothingDispatched(): void;
652
- /** The original dispatcher has a listener for the event. */
653
- assertListening(event: Class<unknown> | string): void;
743
+ /**
744
+ * Laravel's assertListening(event, listener): the original dispatcher has that listener for the event (a class, a
745
+ * [class, method] pair, the same closure, or Function for any closure; wildcard listeners count for a string event).
746
+ * With only the event, any listener will do.
747
+ */
748
+ assertListening(event: Class<unknown> | string, listener?: ExpectedListener): void;
654
749
  /** The recorded events (objects, or names for string events) that match. */
655
750
  dispatched<E>(event: Class<E> | string, callback?: EventFilter<E>): E[];
656
751
  hasDispatched(event: Class<unknown> | string): boolean;
752
+ /** The original dispatcher's listeners for the event, as registered, wildcard ones included for a string event. */
753
+ private listenersFor;
657
754
  private shouldFake;
658
755
  }
659
756
 
@@ -807,6 +904,8 @@ declare class MailFake implements MailManager {
807
904
  mailer(name?: string): Mailer;
808
905
  to(recipients: MailRecipient | MailRecipient[]): PendingMail;
809
906
  send(mailable: Mailable): Promise<SentMessage | undefined>;
907
+ /** Recorded as sent, never queued, like the real sendNow(). */
908
+ sendNow(mailable: Mailable): Promise<SentMessage | undefined>;
810
909
  queue(mailable: Mailable): Promise<void>;
811
910
  extend(_transport: string, _factory: (config: Record<string, unknown>) => MailTransport): void;
812
911
  /** Sent (not queued) at least once; a number asserts the count; a filter gets (mailable, record). */
@@ -828,6 +927,7 @@ declare class MailFake implements MailManager {
828
927
  hasQueued(mailable: Target<Mailable>): boolean;
829
928
  private pending;
830
929
  private sendVia;
930
+ private sendNowVia;
831
931
  private queueVia;
832
932
  private record;
833
933
  private matching;
@@ -987,4 +1087,4 @@ declare const FakeFile: {
987
1087
  image(name: string, width?: number, height?: number): File;
988
1088
  };
989
1089
 
990
- export { AnonymousNotifiable, AssertableInertia, AssertableJson, type BatchRecord, type BootOptions, BusFake, type CountOrFilter, DatabaseMigrations, type DatabaseTestOptions, DatabaseTransactions, type DispatchedEvent, EventFake, type ExpectedErrors, FakeDisk, FakeFile, HttpClient, InteractsWithApplication, InteractsWithConsole, InteractsWithDatabase, type JsonStructure, MailFake, MailRecord, MakesHttpRequests, NotificationFake, PendingCommand, type PushedJob, QueueFake, RefreshDatabase, RefreshDatabaseState, type RequestData, type RequestOptions, type ResponseContext, type ResponseCookie, SHOULD_QUEUE, type SentNotification, StorageFake, TESTING_ENVIRONMENT, type TableOrModel, type Target, TestCase, type TestHooks, TestResponse, type TestTrait, actingAsAuthFactory, addresses, applyEnvironment, cookieHeader, cookiePrefix, decryptCookie, encryptCookie, flatten, guessMimeType, inertiaPageOf, install, isExpired, isQueueable, matches, nameOf, parseSetCookie, recordingExceptionHandler, recordingViewFactory, responseCookies, runCommand, usingInMemoryDatabase };
1090
+ export { AnonymousNotifiable, AssertableInertia, AssertableJson, type BatchRecord, type BootOptions, BusFake, type CountOrFilter, DatabaseMigrations, type DatabaseTestOptions, DatabaseTransactions, type DispatchedEvent, EventFake, type ExpectedErrors, type ExpectedListener, FakeDisk, FakeFile, HttpClient, InteractsWithApplication, InteractsWithConsole, InteractsWithDatabase, InteractsWithTime, type JsonStructure, MailFake, MailRecord, MakesHttpRequests, NotificationFake, PendingCommand, type PushedJob, QueueFake, RefreshDatabase, RefreshDatabaseState, type RequestData, type RequestOptions, type ResponseContext, type ResponseCookie, SHOULD_QUEUE, type SentNotification, StorageFake, TESTING_ENVIRONMENT, type TableOrModel, type Target, TestCase, type TestHooks, TestResponse, type TestTrait, type TravelDate, Wormhole, actingAsAuthFactory, addresses, applyEnvironment, cookieHeader, cookiePrefix, decryptCookie, encryptCookie, flatten, freezeSecond, freezeTime, guessMimeType, inertiaPageOf, install, isExpired, isQueueable, matches, nameOf, parseSetCookie, recordingExceptionHandler, recordingViewFactory, responseCookies, runCommand, travel, travelBack, travelTo, usingInMemoryDatabase };