@dunx/testing 0.1.0
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/LICENSE +201 -0
- package/README.md +150 -0
- package/dist/app.d.ts +32 -0
- package/dist/client.d.ts +31 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +114 -0
- package/dist/index.js.map +13 -0
- package/dist/logger.d.ts +41 -0
- package/dist/server.d.ts +37 -0
- package/package.json +66 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
# @dunx/testing
|
|
2
|
+
|
|
3
|
+
The container an app already has, with named bindings **replaced in place**, plus a
|
|
4
|
+
real `Bun.serve` on port 0. No mocking framework, no fake request object, no
|
|
5
|
+
in-memory transport — Bun binds a socket in about a millisecond, so the thing under
|
|
6
|
+
test is the thing that ships.
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
import { provide } from '@dunx/core';
|
|
10
|
+
import { createTestApp, createTestServer } from '@dunx/testing';
|
|
11
|
+
|
|
12
|
+
// The container only.
|
|
13
|
+
const app = await createTestApp({
|
|
14
|
+
modules: [UsersModule],
|
|
15
|
+
overrides: [provide(Clock, { useValue: new FixedClock('2026-01-01') })],
|
|
16
|
+
});
|
|
17
|
+
expect(app.get(UsersService).today()).toBe('2026-01-01');
|
|
18
|
+
await app.shutdown();
|
|
19
|
+
|
|
20
|
+
// The container behind a real server.
|
|
21
|
+
const server = await createTestServer({
|
|
22
|
+
modules: [ApiModule],
|
|
23
|
+
overrides: [provide(Storage, { useClass: MemoryStorage })],
|
|
24
|
+
prefix: 'api',
|
|
25
|
+
});
|
|
26
|
+
const { status, body } = await server.json<User[]>('api/users');
|
|
27
|
+
await server.close();
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Overrides replace; they never append
|
|
31
|
+
|
|
32
|
+
This is the whole design, and it follows from the container being flat.
|
|
33
|
+
|
|
34
|
+
`@dunx/core` collects every module's registrations into one list and **throws on a
|
|
35
|
+
duplicate token**, naming both modules. So a test override cannot be an extra
|
|
36
|
+
module appended at the end that wins — there is no "wins". It would be a duplicate.
|
|
37
|
+
|
|
38
|
+
`createTestApp` therefore assembles the same flat list the app would have and
|
|
39
|
+
substitutes by token as it goes. Three consequences worth relying on:
|
|
40
|
+
|
|
41
|
+
- **The count per token never changes.** The duplicate-binding check runs
|
|
42
|
+
unmodified, so a test cannot paper over a wiring bug that boot would have caught.
|
|
43
|
+
Two modules binding one token still fails, with the override applied to both.
|
|
44
|
+
- **An override naming a token nobody binds is an error**, not a silent no-op. A
|
|
45
|
+
typo'd token would otherwise leave the suite asserting against the real provider
|
|
46
|
+
it thought it had swapped, which is the failure mode this package exists to
|
|
47
|
+
prevent.
|
|
48
|
+
- **The discarded provider is never instantiated.** Its `useFactory` never runs and
|
|
49
|
+
its `onInit` never fires. Overriding the database does not open a connection to
|
|
50
|
+
the real database — that is the one guarantee here that a hand-rolled fixture
|
|
51
|
+
usually gets wrong, and `app.test.ts` proves it with a factory that throws if it
|
|
52
|
+
is ever called.
|
|
53
|
+
|
|
54
|
+
`Logger` and `RequestContext` are overridable too, even though no module binds
|
|
55
|
+
them: core offers a default for each after every module, and the substitution
|
|
56
|
+
applies there as well.
|
|
57
|
+
|
|
58
|
+
## API
|
|
59
|
+
|
|
60
|
+
| Export | What it is |
|
|
61
|
+
| --------------------------- | ----------------------------------------------------------------------- |
|
|
62
|
+
| `createTestApp(options)` | `Promise<App>` — the core container, overrides applied |
|
|
63
|
+
| `createTestServer(options)` | `Promise<TestServer>` — the same, plus `Bun.serve` on port 0 and a client |
|
|
64
|
+
| `testClient(url)` | `TestClient` — the request helpers against any base URL |
|
|
65
|
+
| `testRoot(modules)` | The synthetic root module, for driving `HttpFactory` yourself |
|
|
66
|
+
| `RecordingLogger` | A `Logger` that keeps entries instead of writing them |
|
|
67
|
+
|
|
68
|
+
`modules` takes one module ref or several; several become the `imports` of one
|
|
69
|
+
synthetic root, so no fixture module has to be written by hand. Anything a module
|
|
70
|
+
ref can be works — a class, or a `DynamicModule` from a `forRoot`.
|
|
71
|
+
|
|
72
|
+
`TestServer` is a `TestClient` plus `app` (the real `HttpApp`, for `app.get(...)`)
|
|
73
|
+
and `close()`. `createTestServer` passes `HttpOptions` through, with two
|
|
74
|
+
differences: `port` is always 0, and **`requestLogging` defaults to `false`** — it
|
|
75
|
+
is on by default in production for good reasons, none of which apply to a suite
|
|
76
|
+
that would otherwise print one JSON line per assertion. Pass
|
|
77
|
+
`requestLogging: true` to test the logging itself.
|
|
78
|
+
|
|
79
|
+
### The client
|
|
80
|
+
|
|
81
|
+
Two methods, because a third would be the start of an assertion DSL:
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
const { status, headers, body } = await server.json<Page>('notes?limit=10');
|
|
85
|
+
await server.json('notes/7', { method: 'PATCH', json: { title: 'edited' } });
|
|
86
|
+
const image = await server.request('avatars/7.png'); // the raw Response
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
`json` on the init object is serialized and sets `content-type: application/json`
|
|
90
|
+
unless `headers` already carries one — one option for every verb, rather than a
|
|
91
|
+
`post`/`put`/`patch` triple. `json()` reads the body as text before parsing, so a
|
|
92
|
+
route that answered 204, HTML or a plain-text error fails with the status,
|
|
93
|
+
content-type and body rather than with `JSON.parse`'s message.
|
|
94
|
+
|
|
95
|
+
### RecordingLogger
|
|
96
|
+
|
|
97
|
+
The `Logger` contract is seven levels of three overloads each, so every suite that
|
|
98
|
+
wants a quiet app would otherwise hand-write the same thirty lines:
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
const logger = new RecordingLogger();
|
|
102
|
+
await createTestApp({
|
|
103
|
+
modules: [PaymentsModule],
|
|
104
|
+
overrides: [provide(Logger, { useValue: logger })],
|
|
105
|
+
});
|
|
106
|
+
expect(logger.at(LogLevel.ERROR)).toEqual([]);
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
It records; it does not interpret. No level filtering, no error promotion, no
|
|
110
|
+
merging of extras — those are `@arkv/logger`'s behaviour, and asserting against a
|
|
111
|
+
reimplementation of them would prove nothing.
|
|
112
|
+
|
|
113
|
+
## Deliberately not here
|
|
114
|
+
|
|
115
|
+
- **A fluent assertion DSL** (`expect(res).toHaveStatus(200)`, supertest-style
|
|
116
|
+
chaining). `status` and a parsed `body` read fine through `expect` already, and a
|
|
117
|
+
matcher library would be a second vocabulary to learn for no new capability.
|
|
118
|
+
- **Provider spies / partial mocks.** `provide(Token, { useValue })` with a class
|
|
119
|
+
the test wrote is smaller than any mocking API, and `bun test` already ships
|
|
120
|
+
`mock()` and `spyOn()` for a method on an instance the container handed back.
|
|
121
|
+
- **A `providers` key on the options.** `{ modules, overrides }` is the shape, on
|
|
122
|
+
purpose: a suite tests the modules an app actually ships. A fixture class that
|
|
123
|
+
needs binding goes in a two-line `@Module`, which is also where it would live if
|
|
124
|
+
it were real.
|
|
125
|
+
- **A fake HTTP dispatcher.** It could only exercise the parts of the request path
|
|
126
|
+
dunx wrote, and not the parts Bun owns — route matching, params, method
|
|
127
|
+
dispatch, upgrades. The real server is cheaper than the lie.
|
|
128
|
+
- **Database fixtures, transactional rollback, seeding.** That is drizzle's
|
|
129
|
+
surface, not this package's. `@dunx/infra/db` binds an in-memory `bun:sqlite`
|
|
130
|
+
with the same driver as production, which is a better fixture than a mock.
|
|
131
|
+
- **A websocket client.** Bun implements `WebSocket` natively, and a gateway test
|
|
132
|
+
is `new WebSocket(server.url.replace('http', 'ws') + '/chat')`. Wrapping that
|
|
133
|
+
would add nothing.
|
|
134
|
+
|
|
135
|
+
## Install it as a devDependency
|
|
136
|
+
|
|
137
|
+
```bash
|
|
138
|
+
bun add -d @dunx/testing
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
`@dunx/core` and `@dunx/http` are `dependencies`, at a **caret** range. What matters
|
|
142
|
+
is that your app and this package resolve to **one copy of `@dunx/core`** — two
|
|
143
|
+
copies means two `Logger` classes and two `RequestContext` classes, so tokens that
|
|
144
|
+
match nothing and overrides that silently replace nothing. A caret range hoists to
|
|
145
|
+
the copy your app already has.
|
|
146
|
+
|
|
147
|
+
Peers would have expressed that better, and were tried first: `bun run --filter '*'`
|
|
148
|
+
derives its build order from `dependencies` only, so a peer-only manifest cannot be
|
|
149
|
+
built in this monorepo at all. The reasoning and the measurement are in
|
|
150
|
+
[ARCHITECTURE.md](../../docs/ARCHITECTURE.md), "Test harness".
|
package/dist/app.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type App, type AppOptions, type DynamicModule, type ModuleRef, type Registration } from '@dunx/core';
|
|
2
|
+
export interface TestAppOptions extends AppOptions {
|
|
3
|
+
/**
|
|
4
|
+
* The graph under test. A single module, or several — they become the `imports`
|
|
5
|
+
* of one synthetic root, so no fixture module has to be written by hand.
|
|
6
|
+
*/
|
|
7
|
+
readonly modules: ModuleRef | readonly ModuleRef[];
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* The root `createTestApp` boots. Exported for the case the harness deliberately
|
|
11
|
+
* does not cover: configuring an `HttpApp` before `listen()` (`enableCors`, `use`,
|
|
12
|
+
* `set`), which means calling `HttpFactory.create(testRoot(modules), …)` directly.
|
|
13
|
+
*/
|
|
14
|
+
export declare const testRoot: (modules: ModuleRef | readonly ModuleRef[]) => DynamicModule;
|
|
15
|
+
/** `exactOptionalPropertyTypes` separates an absent key from an undefined one. */
|
|
16
|
+
export declare const appOptions: (overrides: readonly Registration[] | undefined) => AppOptions;
|
|
17
|
+
/**
|
|
18
|
+
* The container the app under test would have, with the bindings named in
|
|
19
|
+
* `overrides` **replaced in place**.
|
|
20
|
+
*
|
|
21
|
+
* ```ts
|
|
22
|
+
* const app = await createTestApp({
|
|
23
|
+
* modules: [UsersModule],
|
|
24
|
+
* overrides: [provide(Clock, { useValue: new FixedClock('2026-01-01') })],
|
|
25
|
+
* });
|
|
26
|
+
* ```
|
|
27
|
+
*
|
|
28
|
+
* Replacement, not addition: the discarded provider is never instantiated, so an
|
|
29
|
+
* async `useFactory` that would open the real database never runs. An override
|
|
30
|
+
* naming a token nobody binds throws instead of passing silently.
|
|
31
|
+
*/
|
|
32
|
+
export declare const createTestApp: (options: TestAppOptions) => Promise<App>;
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export interface JsonInit extends RequestInit {
|
|
2
|
+
/**
|
|
3
|
+
* Serialized as the request body, with `content-type: application/json` set
|
|
4
|
+
* unless `headers` already carries one. Covers every verb, so there is no
|
|
5
|
+
* `post()`/`put()`/`patch()` triple here. Takes precedence over `body`.
|
|
6
|
+
*/
|
|
7
|
+
readonly json?: unknown;
|
|
8
|
+
}
|
|
9
|
+
export interface JsonResponse<T> {
|
|
10
|
+
readonly status: number;
|
|
11
|
+
readonly headers: Headers;
|
|
12
|
+
readonly body: T;
|
|
13
|
+
}
|
|
14
|
+
export interface TestClient {
|
|
15
|
+
/** The server's base URL, as `listen()` returned it. */
|
|
16
|
+
readonly url: string;
|
|
17
|
+
/** The raw `Response` — for bytes, HTML, or asserting on a header. */
|
|
18
|
+
request(path?: string, init?: JsonInit): Promise<Response>;
|
|
19
|
+
/** Status, headers and parsed body in one await, which is the common assertion. */
|
|
20
|
+
json<T = unknown>(path?: string, init?: JsonInit): Promise<JsonResponse<T>>;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* `fetch` against one base URL, plus the JSON round-trip every suite otherwise
|
|
24
|
+
* rewrites. Deliberately not an assertion DSL: it returns values that `expect`
|
|
25
|
+
* already reads well, so failures point at the assertion rather than at a matcher
|
|
26
|
+
* this package would have to define.
|
|
27
|
+
*
|
|
28
|
+
* `createTestServer` returns one of these already bound to the server it started;
|
|
29
|
+
* this is here for an app booted some other way.
|
|
30
|
+
*/
|
|
31
|
+
export declare const testClient: (url: string) => TestClient;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { createTestApp, testRoot, type TestAppOptions } from './app.js';
|
|
2
|
+
export { testClient, type JsonInit, type JsonResponse, type TestClient, } from './client.js';
|
|
3
|
+
export { RecordingLogger, type RecordedLog } from './logger.js';
|
|
4
|
+
export { createTestServer, type TestServer, type TestServerOptions, } from './server.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/app.ts
|
|
3
|
+
import {
|
|
4
|
+
AppFactory
|
|
5
|
+
} from "@dunx/core";
|
|
6
|
+
|
|
7
|
+
class TestModule {
|
|
8
|
+
}
|
|
9
|
+
var isList = (modules) => Array.isArray(modules);
|
|
10
|
+
var testRoot = (modules) => ({
|
|
11
|
+
module: TestModule,
|
|
12
|
+
imports: isList(modules) ? modules : [modules]
|
|
13
|
+
});
|
|
14
|
+
var appOptions = (overrides) => overrides ? { overrides } : {};
|
|
15
|
+
var createTestApp = (options) => AppFactory.create(testRoot(options.modules), appOptions(options.overrides));
|
|
16
|
+
// src/client.ts
|
|
17
|
+
var target = (base, path) => new URL(path, base);
|
|
18
|
+
var withJson = (init) => {
|
|
19
|
+
const { json, ...rest } = init;
|
|
20
|
+
if (json === undefined)
|
|
21
|
+
return rest;
|
|
22
|
+
const headers = new Headers(init.headers);
|
|
23
|
+
if (!headers.has("content-type")) {
|
|
24
|
+
headers.set("content-type", "application/json");
|
|
25
|
+
}
|
|
26
|
+
return { ...rest, headers, body: JSON.stringify(json) };
|
|
27
|
+
};
|
|
28
|
+
var testClient = (url) => ({
|
|
29
|
+
url,
|
|
30
|
+
request: (path = "", init = {}) => fetch(target(url, path), withJson(init)),
|
|
31
|
+
json: async (path = "", init = {}) => {
|
|
32
|
+
const response = await fetch(target(url, path), withJson(init));
|
|
33
|
+
const text = await response.text();
|
|
34
|
+
try {
|
|
35
|
+
return {
|
|
36
|
+
status: response.status,
|
|
37
|
+
headers: response.headers,
|
|
38
|
+
body: JSON.parse(text)
|
|
39
|
+
};
|
|
40
|
+
} catch {
|
|
41
|
+
const body = text === "" ? "an empty body" : `a ${response.headers.get("content-type") ?? "typeless"} body:
|
|
42
|
+
|
|
43
|
+
` + text.slice(0, 300);
|
|
44
|
+
throw new Error(`${init.method ?? "GET"} ${target(url, path).pathname} answered ` + `${response.status} with ${body}
|
|
45
|
+
|
|
46
|
+
That is not JSON \u2014 use request() ` + "for a response that is not.");
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
// src/logger.ts
|
|
51
|
+
import { Logger, LogLevel } from "@dunx/core";
|
|
52
|
+
|
|
53
|
+
class RecordingLogger extends Logger {
|
|
54
|
+
logLevel = LogLevel.VERBOSE;
|
|
55
|
+
entries = [];
|
|
56
|
+
verbose(message, ...params) {
|
|
57
|
+
this.#record(LogLevel.VERBOSE, message, params);
|
|
58
|
+
}
|
|
59
|
+
debug(message, ...params) {
|
|
60
|
+
this.#record(LogLevel.DEBUG, message, params);
|
|
61
|
+
}
|
|
62
|
+
info(message, ...params) {
|
|
63
|
+
this.#record(LogLevel.INFO, message, params);
|
|
64
|
+
}
|
|
65
|
+
log(message, ...params) {
|
|
66
|
+
this.#record(LogLevel.INFO, message, params);
|
|
67
|
+
}
|
|
68
|
+
warn(message, ...params) {
|
|
69
|
+
this.#record(LogLevel.WARN, message, params);
|
|
70
|
+
}
|
|
71
|
+
error(message, ...params) {
|
|
72
|
+
this.#record(LogLevel.ERROR, message, params);
|
|
73
|
+
}
|
|
74
|
+
fatal(message, ...params) {
|
|
75
|
+
this.#record(LogLevel.FATAL, message, params);
|
|
76
|
+
}
|
|
77
|
+
at(level) {
|
|
78
|
+
return this.entries.filter((entry) => entry.level === level);
|
|
79
|
+
}
|
|
80
|
+
clear() {
|
|
81
|
+
this.entries.length = 0;
|
|
82
|
+
}
|
|
83
|
+
#record(level, message, params) {
|
|
84
|
+
this.entries.push({ level, message, params });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
// src/server.ts
|
|
88
|
+
import { HttpFactory } from "@dunx/http";
|
|
89
|
+
var createTestServer = async (options) => {
|
|
90
|
+
const { modules, overrides, prefix, requestLogging, ...http } = options;
|
|
91
|
+
const app = await HttpFactory.create(testRoot(modules), {
|
|
92
|
+
...http,
|
|
93
|
+
...appOptions(overrides),
|
|
94
|
+
requestLogging: requestLogging ?? false,
|
|
95
|
+
port: 0
|
|
96
|
+
});
|
|
97
|
+
if (prefix !== undefined)
|
|
98
|
+
app.setGlobalPrefix(prefix);
|
|
99
|
+
return {
|
|
100
|
+
...testClient(await app.listen()),
|
|
101
|
+
app,
|
|
102
|
+
close: () => app.shutdown()
|
|
103
|
+
};
|
|
104
|
+
};
|
|
105
|
+
export {
|
|
106
|
+
testRoot,
|
|
107
|
+
testClient,
|
|
108
|
+
createTestServer,
|
|
109
|
+
createTestApp,
|
|
110
|
+
RecordingLogger
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
//# debugId=5E77DA71121848D164756E2164756E21
|
|
114
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/app.ts", "../src/client.ts", "../src/logger.ts", "../src/server.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import {\n AppFactory,\n type App,\n type AppOptions,\n type DynamicModule,\n type ModuleRef,\n type Registration,\n} from '@dunx/core';\n\n/**\n * The synthetic root. A named class rather than an object literal for the same\n * reason `@dunx/http`'s `HttpModule` is one: it is what a duplicate-binding error\n * would name if the harness itself ever bound anything.\n */\nclass TestModule {}\n\nexport interface TestAppOptions extends AppOptions {\n /**\n * The graph under test. A single module, or several — they become the `imports`\n * of one synthetic root, so no fixture module has to be written by hand.\n */\n readonly modules: ModuleRef | readonly ModuleRef[];\n}\n\nconst isList = (\n modules: ModuleRef | readonly ModuleRef[],\n): modules is readonly ModuleRef[] => Array.isArray(modules);\n\n/**\n * The root `createTestApp` boots. Exported for the case the harness deliberately\n * does not cover: configuring an `HttpApp` before `listen()` (`enableCors`, `use`,\n * `set`), which means calling `HttpFactory.create(testRoot(modules), …)` directly.\n */\nexport const testRoot = (\n modules: ModuleRef | readonly ModuleRef[],\n): DynamicModule => ({\n module: TestModule,\n imports: isList(modules) ? modules : [modules],\n});\n\n/** `exactOptionalPropertyTypes` separates an absent key from an undefined one. */\nexport const appOptions = (\n overrides: readonly Registration[] | undefined,\n): AppOptions => (overrides ? { overrides } : {});\n\n/**\n * The container the app under test would have, with the bindings named in\n * `overrides` **replaced in place**.\n *\n * ```ts\n * const app = await createTestApp({\n * modules: [UsersModule],\n * overrides: [provide(Clock, { useValue: new FixedClock('2026-01-01') })],\n * });\n * ```\n *\n * Replacement, not addition: the discarded provider is never instantiated, so an\n * async `useFactory` that would open the real database never runs. An override\n * naming a token nobody binds throws instead of passing silently.\n */\nexport const createTestApp = (options: TestAppOptions): Promise<App> =>\n AppFactory.create(testRoot(options.modules), appOptions(options.overrides));\n",
|
|
6
|
+
"export interface JsonInit extends RequestInit {\n /**\n * Serialized as the request body, with `content-type: application/json` set\n * unless `headers` already carries one. Covers every verb, so there is no\n * `post()`/`put()`/`patch()` triple here. Takes precedence over `body`.\n */\n readonly json?: unknown;\n}\n\nexport interface JsonResponse<T> {\n readonly status: number;\n readonly headers: Headers;\n readonly body: T;\n}\n\nexport interface TestClient {\n /** The server's base URL, as `listen()` returned it. */\n readonly url: string;\n /** The raw `Response` — for bytes, HTML, or asserting on a header. */\n request(path?: string, init?: JsonInit): Promise<Response>;\n /** Status, headers and parsed body in one await, which is the common assertion. */\n json<T = unknown>(path?: string, init?: JsonInit): Promise<JsonResponse<T>>;\n}\n\nconst target = (base: string, path: string): URL => new URL(path, base);\n\nconst withJson = (init: JsonInit): RequestInit => {\n const { json, ...rest } = init;\n if (json === undefined) return rest;\n\n const headers = new Headers(init.headers);\n if (!headers.has('content-type')) {\n headers.set('content-type', 'application/json');\n }\n return { ...rest, headers, body: JSON.stringify(json) };\n};\n\n/**\n * `fetch` against one base URL, plus the JSON round-trip every suite otherwise\n * rewrites. Deliberately not an assertion DSL: it returns values that `expect`\n * already reads well, so failures point at the assertion rather than at a matcher\n * this package would have to define.\n *\n * `createTestServer` returns one of these already bound to the server it started;\n * this is here for an app booted some other way.\n */\nexport const testClient = (url: string): TestClient => ({\n url,\n request: (path = '', init: JsonInit = {}) =>\n fetch(target(url, path), withJson(init)),\n json: async <T>(path = '', init: JsonInit = {}): Promise<JsonResponse<T>> => {\n const response = await fetch(target(url, path), withJson(init));\n // Read as text first: a route that answered 204, HTML or a plain-text error\n // would otherwise fail with `JSON.parse`'s message and none of the context\n // needed to see why.\n const text = await response.text();\n try {\n return {\n status: response.status,\n headers: response.headers,\n body: JSON.parse(text) as T,\n };\n } catch {\n const body =\n text === ''\n ? 'an empty body'\n : `a ${response.headers.get('content-type') ?? 'typeless'} body:\\n\\n` +\n text.slice(0, 300);\n throw new Error(\n `${init.method ?? 'GET'} ${target(url, path).pathname} answered ` +\n `${response.status} with ${body}\\n\\nThat is not JSON — use request() ` +\n 'for a response that is not.',\n );\n }\n },\n});\n",
|
|
7
|
+
"import { Logger, LogLevel, type LogMessage } from '@dunx/core';\n\nexport interface RecordedLog {\n readonly level: LogLevel;\n readonly message: LogMessage;\n readonly params: readonly unknown[];\n}\n\n/**\n * A {@link Logger} that keeps entries instead of writing them, so a suite can\n * assert on what was logged and stays quiet when it does not care.\n *\n * It is here because the contract is seven levels of three overloads each: every\n * suite that wants a silent logger would otherwise hand-write the same thirty\n * lines. Nothing is interpreted — no level filtering, no error promotion, no\n * merging of extras — because those are the backing logger's behaviour and\n * asserting against a reimplementation of them would prove nothing.\n *\n * ```ts\n * const logger = new RecordingLogger();\n * await createTestApp({\n * modules: [UsersModule],\n * overrides: [provide(Logger, { useValue: logger })],\n * });\n * expect(logger.at(LogLevel.WARN)).toHaveLength(0);\n * ```\n */\nexport class RecordingLogger extends Logger {\n /** Everything is recorded, so a suite can assert on a `verbose` call too. */\n readonly logLevel: LogLevel = LogLevel.VERBOSE;\n readonly entries: RecordedLog[] = [];\n\n verbose(message: LogMessage, ...params: unknown[]): void {\n this.#record(LogLevel.VERBOSE, message, params);\n }\n\n debug(message: LogMessage, ...params: unknown[]): void {\n this.#record(LogLevel.DEBUG, message, params);\n }\n\n info(message: LogMessage, ...params: unknown[]): void {\n this.#record(LogLevel.INFO, message, params);\n }\n\n /** @deprecated Use {@link RecordingLogger.info}. Recorded as `info` either way. */\n log(message: LogMessage, ...params: unknown[]): void {\n this.#record(LogLevel.INFO, message, params);\n }\n\n warn(message: LogMessage, ...params: unknown[]): void {\n this.#record(LogLevel.WARN, message, params);\n }\n\n error(message: LogMessage, ...params: unknown[]): void {\n this.#record(LogLevel.ERROR, message, params);\n }\n\n fatal(message: LogMessage, ...params: unknown[]): void {\n this.#record(LogLevel.FATAL, message, params);\n }\n\n at(level: LogLevel): readonly RecordedLog[] {\n return this.entries.filter((entry) => entry.level === level);\n }\n\n clear(): void {\n this.entries.length = 0;\n }\n\n #record(\n level: LogLevel,\n message: LogMessage,\n params: readonly unknown[],\n ): void {\n this.entries.push({ level, message, params });\n }\n}\n",
|
|
8
|
+
"import { HttpFactory, type HttpApp, type HttpOptions } from '@dunx/http';\nimport { appOptions, testRoot, type TestAppOptions } from './app.js';\nimport { testClient, type TestClient } from './client.js';\n\nexport interface TestServerOptions\n extends TestAppOptions, Omit<HttpOptions, 'port' | 'overrides'> {\n /**\n * `setGlobalPrefix`, applied before `listen()` so the client's URLs carry it.\n *\n * Explicitly `| undefined`, unlike the rest of the options: a suite that runs\n * the same fixture prefixed and unprefixed passes a variable here, and under\n * `exactOptionalPropertyTypes` that is otherwise a conditional spread. \"No\n * prefix\" and \"absent\" mean the same thing, so nothing is lost by allowing it.\n */\n readonly prefix?: string | undefined;\n}\n\nexport interface TestServer extends TestClient {\n readonly app: HttpApp;\n /** `app.shutdown()` — stops the server, then tears the container down. */\n close(): Promise<void>;\n}\n\n/**\n * A **real** `Bun.serve` on port 0, with the same override semantics as\n * {@link createTestApp}. Nothing is faked: `Bun.serve` binds in about a\n * millisecond, and a fake would only be able to prove the parts of the request\n * path dunx wrote rather than the parts Bun owns — routing, params, method\n * dispatch, upgrades.\n *\n * ```ts\n * const server = await createTestServer({ modules: [ApiModule], prefix: 'api' });\n * const { status, body } = await server.json('api/users');\n * await server.close();\n * ```\n *\n * Request logging is **off** unless asked for: it is on by default in production\n * for good reasons, none of which apply to a suite that would print one JSON line\n * per assertion.\n */\nexport const createTestServer = async (\n options: TestServerOptions,\n): Promise<TestServer> => {\n const { modules, overrides, prefix, requestLogging, ...http } = options;\n\n const app = await HttpFactory.create(testRoot(modules), {\n ...http,\n ...appOptions(overrides),\n requestLogging: requestLogging ?? false,\n port: 0,\n });\n if (prefix !== undefined) app.setGlobalPrefix(prefix);\n\n return {\n ...testClient(await app.listen()),\n app,\n close: () => app.shutdown(),\n };\n};\n"
|
|
9
|
+
],
|
|
10
|
+
"mappings": "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",
|
|
11
|
+
"debugId": "5E77DA71121848D164756E2164756E21",
|
|
12
|
+
"names": []
|
|
13
|
+
}
|
package/dist/logger.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { Logger, LogLevel, type LogMessage } from '@dunx/core';
|
|
2
|
+
export interface RecordedLog {
|
|
3
|
+
readonly level: LogLevel;
|
|
4
|
+
readonly message: LogMessage;
|
|
5
|
+
readonly params: readonly unknown[];
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* A {@link Logger} that keeps entries instead of writing them, so a suite can
|
|
9
|
+
* assert on what was logged and stays quiet when it does not care.
|
|
10
|
+
*
|
|
11
|
+
* It is here because the contract is seven levels of three overloads each: every
|
|
12
|
+
* suite that wants a silent logger would otherwise hand-write the same thirty
|
|
13
|
+
* lines. Nothing is interpreted — no level filtering, no error promotion, no
|
|
14
|
+
* merging of extras — because those are the backing logger's behaviour and
|
|
15
|
+
* asserting against a reimplementation of them would prove nothing.
|
|
16
|
+
*
|
|
17
|
+
* ```ts
|
|
18
|
+
* const logger = new RecordingLogger();
|
|
19
|
+
* await createTestApp({
|
|
20
|
+
* modules: [UsersModule],
|
|
21
|
+
* overrides: [provide(Logger, { useValue: logger })],
|
|
22
|
+
* });
|
|
23
|
+
* expect(logger.at(LogLevel.WARN)).toHaveLength(0);
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
export declare class RecordingLogger extends Logger {
|
|
27
|
+
#private;
|
|
28
|
+
/** Everything is recorded, so a suite can assert on a `verbose` call too. */
|
|
29
|
+
readonly logLevel: LogLevel;
|
|
30
|
+
readonly entries: RecordedLog[];
|
|
31
|
+
verbose(message: LogMessage, ...params: unknown[]): void;
|
|
32
|
+
debug(message: LogMessage, ...params: unknown[]): void;
|
|
33
|
+
info(message: LogMessage, ...params: unknown[]): void;
|
|
34
|
+
/** @deprecated Use {@link RecordingLogger.info}. Recorded as `info` either way. */
|
|
35
|
+
log(message: LogMessage, ...params: unknown[]): void;
|
|
36
|
+
warn(message: LogMessage, ...params: unknown[]): void;
|
|
37
|
+
error(message: LogMessage, ...params: unknown[]): void;
|
|
38
|
+
fatal(message: LogMessage, ...params: unknown[]): void;
|
|
39
|
+
at(level: LogLevel): readonly RecordedLog[];
|
|
40
|
+
clear(): void;
|
|
41
|
+
}
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { type HttpApp, type HttpOptions } from '@dunx/http';
|
|
2
|
+
import { type TestAppOptions } from './app.js';
|
|
3
|
+
import { type TestClient } from './client.js';
|
|
4
|
+
export interface TestServerOptions extends TestAppOptions, Omit<HttpOptions, 'port' | 'overrides'> {
|
|
5
|
+
/**
|
|
6
|
+
* `setGlobalPrefix`, applied before `listen()` so the client's URLs carry it.
|
|
7
|
+
*
|
|
8
|
+
* Explicitly `| undefined`, unlike the rest of the options: a suite that runs
|
|
9
|
+
* the same fixture prefixed and unprefixed passes a variable here, and under
|
|
10
|
+
* `exactOptionalPropertyTypes` that is otherwise a conditional spread. "No
|
|
11
|
+
* prefix" and "absent" mean the same thing, so nothing is lost by allowing it.
|
|
12
|
+
*/
|
|
13
|
+
readonly prefix?: string | undefined;
|
|
14
|
+
}
|
|
15
|
+
export interface TestServer extends TestClient {
|
|
16
|
+
readonly app: HttpApp;
|
|
17
|
+
/** `app.shutdown()` — stops the server, then tears the container down. */
|
|
18
|
+
close(): Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* A **real** `Bun.serve` on port 0, with the same override semantics as
|
|
22
|
+
* {@link createTestApp}. Nothing is faked: `Bun.serve` binds in about a
|
|
23
|
+
* millisecond, and a fake would only be able to prove the parts of the request
|
|
24
|
+
* path dunx wrote rather than the parts Bun owns — routing, params, method
|
|
25
|
+
* dispatch, upgrades.
|
|
26
|
+
*
|
|
27
|
+
* ```ts
|
|
28
|
+
* const server = await createTestServer({ modules: [ApiModule], prefix: 'api' });
|
|
29
|
+
* const { status, body } = await server.json('api/users');
|
|
30
|
+
* await server.close();
|
|
31
|
+
* ```
|
|
32
|
+
*
|
|
33
|
+
* Request logging is **off** unless asked for: it is on by default in production
|
|
34
|
+
* for good reasons, none of which apply to a suite that would print one JSON line
|
|
35
|
+
* per assertion.
|
|
36
|
+
*/
|
|
37
|
+
export declare const createTestServer: (options: TestServerOptions) => Promise<TestServer>;
|
package/package.json
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@dunx/testing",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Test harness for dunx apps: a container with providers replaced in place, and a real Bun.serve on port 0",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"bun",
|
|
7
|
+
"dependency-injection",
|
|
8
|
+
"dunx",
|
|
9
|
+
"integration-testing",
|
|
10
|
+
"mock",
|
|
11
|
+
"override",
|
|
12
|
+
"testing"
|
|
13
|
+
],
|
|
14
|
+
"homepage": "https://github.com/petarzarkov/dunx/tree/main/packages/testing#readme",
|
|
15
|
+
"license": "MIT",
|
|
16
|
+
"author": {
|
|
17
|
+
"name": "Petar Zarkov",
|
|
18
|
+
"email": "pzarko1@gmail.com",
|
|
19
|
+
"url": "https://github.com/petarzarkov"
|
|
20
|
+
},
|
|
21
|
+
"repository": {
|
|
22
|
+
"type": "git",
|
|
23
|
+
"url": "git+https://github.com/petarzarkov/dunx.git",
|
|
24
|
+
"directory": "packages/testing"
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"LICENSE",
|
|
28
|
+
"README.md",
|
|
29
|
+
"dist"
|
|
30
|
+
],
|
|
31
|
+
"type": "module",
|
|
32
|
+
"main": "./dist/index.js",
|
|
33
|
+
"types": "./dist/index.d.ts",
|
|
34
|
+
"exports": {
|
|
35
|
+
".": {
|
|
36
|
+
"types": "./dist/index.d.ts",
|
|
37
|
+
"import": "./dist/index.js"
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
"publishConfig": {
|
|
41
|
+
"access": "public"
|
|
42
|
+
},
|
|
43
|
+
"scripts": {
|
|
44
|
+
"build": "bun ../../scripts/build-package.ts",
|
|
45
|
+
"test": "bun test --bail",
|
|
46
|
+
"test:cov": "bun test --coverage",
|
|
47
|
+
"typecheck": "tsc --noEmit"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@dunx/core": "workspace:*",
|
|
51
|
+
"@dunx/http": "workspace:*"
|
|
52
|
+
},
|
|
53
|
+
"peerDependencies": {
|
|
54
|
+
"@dunx/core": "0.1.0",
|
|
55
|
+
"@dunx/http": "0.1.0",
|
|
56
|
+
"@types/bun": ">=1.3.0"
|
|
57
|
+
},
|
|
58
|
+
"peerDependenciesMeta": {
|
|
59
|
+
"@types/bun": {
|
|
60
|
+
"optional": true
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
"engines": {
|
|
64
|
+
"bun": ">=1.3.0"
|
|
65
|
+
}
|
|
66
|
+
}
|