|
| 1 | +/* eslint no-unused-expressions: "off" */ |
| 2 | + |
| 3 | +// Test tools |
| 4 | +const chai = require('chai') |
| 5 | + |
| 6 | +const { |
| 7 | + fetch, |
| 8 | + MockAgent, |
| 9 | + setGlobalDispatcher, |
| 10 | + Headers |
| 11 | +} = require('../../index.js') |
| 12 | + |
| 13 | +const { expect } = chai |
| 14 | + |
| 15 | +describe('node-fetch with MockAgent', () => { |
| 16 | + it('should match the url', async () => { |
| 17 | + const mockAgent = new MockAgent() |
| 18 | + setGlobalDispatcher(mockAgent) |
| 19 | + const mockPool = mockAgent.get('http://localhost:3000') |
| 20 | + |
| 21 | + mockPool |
| 22 | + .intercept({ |
| 23 | + path: '/test', |
| 24 | + method: 'GET', |
| 25 | + }) |
| 26 | + .reply(200, { success: true }) |
| 27 | + .persist() |
| 28 | + |
| 29 | + const res = await fetch('http://localhost:3000/test', { |
| 30 | + method: 'GET' |
| 31 | + }) |
| 32 | + |
| 33 | + expect(res.status).to.equal(200) |
| 34 | + expect(await res.json()).to.deep.equal({ success: true }) |
| 35 | + }) |
| 36 | + |
| 37 | + it('should match the body', async () => { |
| 38 | + const mockAgent = new MockAgent() |
| 39 | + setGlobalDispatcher(mockAgent) |
| 40 | + const mockPool = mockAgent.get('http://localhost:3000') |
| 41 | + |
| 42 | + mockPool |
| 43 | + .intercept({ |
| 44 | + path: '/test', |
| 45 | + method: 'POST', |
| 46 | + body: (value) => { |
| 47 | + return value === 'request body' |
| 48 | + } |
| 49 | + }) |
| 50 | + .reply(200, { success: true }) |
| 51 | + .persist() |
| 52 | + |
| 53 | + const res = await fetch('http://localhost:3000/test', { |
| 54 | + method: 'POST', |
| 55 | + body: 'request body' |
| 56 | + }) |
| 57 | + |
| 58 | + expect(res.status).to.equal(200) |
| 59 | + expect(await res.json()).to.deep.equal({ success: true }) |
| 60 | + }) |
| 61 | + |
| 62 | + it('should match the headers', async () => { |
| 63 | + const mockAgent = new MockAgent() |
| 64 | + setGlobalDispatcher(mockAgent) |
| 65 | + const mockPool = mockAgent.get('http://localhost:3000') |
| 66 | + |
| 67 | + mockPool |
| 68 | + .intercept({ |
| 69 | + path: '/test', |
| 70 | + method: 'GET', |
| 71 | + headers: { |
| 72 | + 'User-Agent': /^undici$/, |
| 73 | + } |
| 74 | + }) |
| 75 | + .reply(200, { success: true }) |
| 76 | + .persist() |
| 77 | + |
| 78 | + const res = await fetch('http://localhost:3000/test', { |
| 79 | + method: 'GET', |
| 80 | + headers: new Headers({ 'User-Agent': 'undici' }) |
| 81 | + }) |
| 82 | + |
| 83 | + expect(res.status).to.equal(200) |
| 84 | + expect(await res.json()).to.deep.equal({ success: true }) |
| 85 | + }) |
| 86 | +}) |
0 commit comments