|
| 1 | +import 'mocha'; |
| 2 | +import { expect } from 'chai'; |
| 3 | +import { ApiResponseError, TwitterApiv2 } from '../src'; |
| 4 | +import { FakeX } from './fake-x'; |
| 5 | + |
| 6 | +const me = { id: '12', name: 'Jack', username: 'jack' }; |
| 7 | + |
| 8 | +describe('Client (offline: a fake X answers)', () => { |
| 9 | + let x: FakeX; |
| 10 | + |
| 11 | + before(async () => { |
| 12 | + x = await FakeX.start(); |
| 13 | + }); |
| 14 | + |
| 15 | + after(() => x.close()); |
| 16 | + |
| 17 | + beforeEach(() => x.reset()); |
| 18 | + |
| 19 | + describe('Current user cache', () => { |
| 20 | + it('Should cache the current user, with one request for two calls', async () => { |
| 21 | + x.on('GET', '/2/users/me', { body: { data: me } }); |
| 22 | + const client = x.client(); |
| 23 | + |
| 24 | + expect(await client.currentUserV2()).to.deep.equal({ data: me }); |
| 25 | + expect(await client.currentUserV2()).to.deep.equal({ data: me }); |
| 26 | + expect(x.requests).to.have.length(1); |
| 27 | + }); |
| 28 | + |
| 29 | + it('Should not cache a failure, so that the next call retries', async () => { |
| 30 | + x.on('GET', '/2/users/me', { status: 503, body: { title: 'Service Unavailable', type: 'about:blank', status: 503, detail: 'Service Unavailable' } }); |
| 31 | + const client = x.client(); |
| 32 | + |
| 33 | + const error = await client.v2.bookmark('20').then(() => null, (e: Error) => e); |
| 34 | + expect(error).to.be.instanceOf(ApiResponseError); |
| 35 | + expect((error as ApiResponseError).code).to.equal(503); |
| 36 | + |
| 37 | + x.on('GET', '/2/users/me', { body: { data: me } }); |
| 38 | + await client.v2.bookmark('20'); |
| 39 | + |
| 40 | + expect(x.requests.map(({ method, url }) => `${method} ${url.pathname}`)).to.deep.equal([ |
| 41 | + 'GET /2/users/me', |
| 42 | + 'GET /2/users/me', |
| 43 | + 'POST /2/users/12/bookmarks', |
| 44 | + ]); |
| 45 | + }); |
| 46 | + }); |
| 47 | + |
| 48 | + it('cloneWithPrefix() should send the requests of the clone to the new prefix', async () => { |
| 49 | + x.on('GET', '/2/users/me', { body: { data: me } }); |
| 50 | + const client = x.client(); |
| 51 | + |
| 52 | + const clone = client.v2.cloneWithPrefix('https://api.twitter.com/2/'); |
| 53 | + expect(clone).to.be.instanceOf(TwitterApiv2); |
| 54 | + |
| 55 | + await clone.me(); |
| 56 | + await client.v2.me(); |
| 57 | + |
| 58 | + expect(x.requests.map(({ url }) => url.href)).to.deep.equal([ |
| 59 | + 'https://api.twitter.com/2/users/me', |
| 60 | + 'https://api.x.com/2/users/me', |
| 61 | + ]); |
| 62 | + }); |
| 63 | +}); |
0 commit comments