-
Notifications
You must be signed in to change notification settings - Fork 90
/
fetch.test.ts
71 lines (56 loc) · 1.91 KB
/
fetch.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
jest.mock("request", () => jest.fn())
import request, { Request } from "request"
const mockRequest = (request as any) as jest.Mock<Request>
import fetch from "../../apis/fetch"
declare const expectPromiseRejectionToMatch: any
it("tries to parse the response when there is a String and resolves with it", async () => {
const reqResponse = {
statusCode: 200,
body: `{ "foo": "bar" }`,
}
mockRequest.mockImplementationOnce((_, __, callback) => {
callback(null, reqResponse)
})
const response = await fetch("foo/bar")
expect(response.body.foo).toBe("bar")
})
it("rejects request errors", async () => {
mockRequest.mockImplementationOnce((_, __, ___) => {
throw new Error("bad")
})
expectPromiseRejectionToMatch(fetch("foo/bar"), /bad/)
})
it("tries to parse the response when there is a String and resolves with it (2)", async () => {
const reqResponse = {
statusCode: 200,
body: `{ not json }`,
}
mockRequest.mockImplementationOnce((_, __, callback) => {
callback(null, reqResponse)
})
return expectPromiseRejectionToMatch(fetch("foo/bar"), /Unexpected token/)
})
it("tries to parse the response when there is a String and resolves with it (3)", () => {
const reqResponse = {
statusCode: 400,
request: {
uri: {
href: "http://api.artsy.net/api/v1/me",
},
},
body: `{ "type": "other_error", "message": "undefined method \`[]' for nil:NilClass" }`,
}
mockRequest.mockImplementationOnce((_, __, callback) =>
callback(null, reqResponse)
)
expect.assertions(3)
return fetch("foo/bar").catch((error) => {
expect(error.message).toEqual(
`http://api.artsy.net/api/v1/me - { "type": "other_error", "message": "undefined method \`[]' for nil:NilClass" }`
)
expect(error.statusCode).toEqual(400)
expect(error.body).toEqual(
`{ "type": "other_error", "message": "undefined method \`[]' for nil:NilClass" }`
)
})
})