|
| 1 | +const mockAxios = require("axios"); |
| 2 | +const getS2SToken = require("../index"); |
| 3 | + |
| 4 | +const validHeaders = { |
| 5 | + "s2s-url": "http://stuff/lease", |
| 6 | + "service-name": "my-name", |
| 7 | + "service-key": "the-key" |
| 8 | +}; |
| 9 | + |
| 10 | +describe("getS2SToken function", () => { |
| 11 | + beforeEach(() => { |
| 12 | + mockAxios.mockReset(); |
| 13 | + }); |
| 14 | + |
| 15 | + it("should return an error response when the header parameters are invalid", async () => { |
| 16 | + const done = jest.fn(); |
| 17 | + const ctx = { done }; |
| 18 | + await getS2SToken(ctx, { headers: {} }); |
| 19 | + |
| 20 | + expect(ctx.res.status).toEqual(500); |
| 21 | + }); |
| 22 | + |
| 23 | + it("should query the s2s server with the right payload", async () => { |
| 24 | + const done = jest.fn(); |
| 25 | + const ctx = { done }; |
| 26 | + const req = { headers: validHeaders }; |
| 27 | + await getS2SToken(ctx, req); |
| 28 | + |
| 29 | + expect(mockAxios).toHaveBeenCalledWith( |
| 30 | + expect.objectContaining({ |
| 31 | + body: expect.any(String), |
| 32 | + headers: { |
| 33 | + "Content-Type": "application/json" |
| 34 | + }, |
| 35 | + method: "post", |
| 36 | + url: "http://stuff/lease" |
| 37 | + }) |
| 38 | + ); |
| 39 | + |
| 40 | + const calledBody = JSON.parse(mockAxios.mock.calls[0][0].body); |
| 41 | + |
| 42 | + expect(calledBody).toHaveProperty("microservice", "my-name"); |
| 43 | + expect(calledBody).toHaveProperty("oneTimePassword"); |
| 44 | + }); |
| 45 | + |
| 46 | + it("should return an error response when the s2s server request fails", async () => { |
| 47 | + const done = jest.fn(); |
| 48 | + const ctx = { done }; |
| 49 | + const req = { headers: validHeaders }; |
| 50 | + mockAxios.mockImplementationOnce(() => Promise.reject(new Error("woops"))); |
| 51 | + await getS2SToken(ctx, req); |
| 52 | + |
| 53 | + expect(ctx.res.status).toEqual(500); |
| 54 | + }); |
| 55 | + |
| 56 | + it("should return a response with the token received from the s2s server", async () => { |
| 57 | + const done = jest.fn(); |
| 58 | + const ctx = { done }; |
| 59 | + const req = { headers: validHeaders }; |
| 60 | + mockAxios.mockImplementationOnce(() => |
| 61 | + Promise.resolve({ |
| 62 | + text: () => "hey" |
| 63 | + }) |
| 64 | + ); |
| 65 | + await getS2SToken(ctx, req); |
| 66 | + |
| 67 | + expect(ctx.res).toEqual({ status: 200, body: { token: "hey" } }); |
| 68 | + }); |
| 69 | +}); |
0 commit comments