1 | import { rejects, strictEqual } from 'node:assert'
|
2 | import { describe, it } from 'mocha'
|
3 | import protoFetch from '../index.js'
|
4 |
|
5 | describe('proto-fetch', () => {
|
6 | it('should be a factory', () => {
|
7 | strictEqual(typeof protoFetch, 'function')
|
8 | })
|
9 |
|
10 | it('should reject the request if the protocol is unknown', async () => {
|
11 | const fetch = protoFetch({})
|
12 |
|
13 | await rejects(fetch('http://example.org/'))
|
14 | })
|
15 |
|
16 | it('should use the fetch implementation for the protocol in the given URL', async () => {
|
17 | let touched
|
18 |
|
19 | const fileFetch = () => {}
|
20 |
|
21 | const httpFetch = () => {
|
22 | touched = true
|
23 | }
|
24 |
|
25 | const fetch = protoFetch({
|
26 | file: fileFetch,
|
27 | http: httpFetch
|
28 | })
|
29 |
|
30 | await fetch('http://example.org/')
|
31 |
|
32 | strictEqual(touched, true)
|
33 | })
|
34 |
|
35 | it('should use the default fetch implementation for relative URLs', async () => {
|
36 | let touched
|
37 |
|
38 | const defaultFetch = () => {
|
39 | touched = true
|
40 | }
|
41 |
|
42 | const fileFetch = () => {}
|
43 |
|
44 | const fetch = protoFetch({
|
45 | [null]: defaultFetch,
|
46 | file: fileFetch
|
47 | })
|
48 |
|
49 | await fetch('/')
|
50 |
|
51 | strictEqual(touched, true)
|
52 | })
|
53 |
|
54 | it('should forward the url arguments', async () => {
|
55 | let actualUrl
|
56 |
|
57 | const url = 'http://example.org/'
|
58 |
|
59 | const httpFetch = url => {
|
60 | actualUrl = url
|
61 | }
|
62 |
|
63 | const fetch = protoFetch({
|
64 | http: httpFetch
|
65 | })
|
66 |
|
67 | await fetch(url)
|
68 |
|
69 | strictEqual(actualUrl, url)
|
70 | })
|
71 |
|
72 | it('should forward the options argument', async () => {
|
73 | let actualOptions
|
74 |
|
75 | const options = {}
|
76 |
|
77 | const httpFetch = (url, options) => {
|
78 | actualOptions = options
|
79 | }
|
80 |
|
81 | const fetch = protoFetch({
|
82 | http: httpFetch
|
83 | })
|
84 |
|
85 | await fetch('http://example.org/', options)
|
86 |
|
87 | strictEqual(actualOptions, options)
|
88 | })
|
89 |
|
90 | it('should support URIs', async () => {
|
91 | let actualUri
|
92 |
|
93 | const url = 'file:package.json'
|
94 |
|
95 | const fileFetch = (url, options) => {
|
96 | actualUri = url
|
97 | }
|
98 |
|
99 | const fetch = protoFetch({
|
100 | file: fileFetch
|
101 | })
|
102 |
|
103 | await fetch(url)
|
104 |
|
105 | strictEqual(actualUri, url)
|
106 | })
|
107 |
|
108 | it('should forward the return value', async () => {
|
109 | const res = {}
|
110 |
|
111 | const httpFetch = () => res
|
112 |
|
113 | const fetch = protoFetch({
|
114 | http: httpFetch
|
115 | })
|
116 |
|
117 | const result = await fetch('http://example.org/')
|
118 |
|
119 | strictEqual(result, res)
|
120 | })
|
121 | })
|