Skip to content

Commit 9413c37

Browse files
authored
feat: add injectable _fetch for React Native compatibility (#79)
1 parent 3d72ca2 commit 9413c37

2 files changed

Lines changed: 26 additions & 3 deletions

File tree

spec/bugsplat.spec.ts

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,10 +99,32 @@ describe('BugSplat', function () {
9999
bugsplat = new BugSplat(database, appName, appVersion);
100100
// @ts-expect-error -- accessing private field for test mocking
101101
bugsplat._formData = () => fakeFormData;
102-
fetchSpy = vi.spyOn(globalThis, 'fetch') as unknown as Mock;
102+
fetchSpy = vi.fn();
103+
// @ts-expect-error -- accessing private field for test mocking
104+
bugsplat._fetch = fetchSpy;
103105
});
104106

105107
describe('post', () => {
108+
it('should use injectable _fetch instead of globalThis.fetch', async () => {
109+
const customFetch = vi.fn().mockResolvedValue(fakeSuccessResponseBody);
110+
const globalFetchSpy = vi.fn().mockResolvedValue(fakeSuccessResponseBody);
111+
vi.stubGlobal('fetch', globalFetchSpy);
112+
// @ts-expect-error -- accessing private field for test
113+
bugsplat._fetch = customFetch;
114+
115+
await bugsplat.post(new Error('BugSplat!'));
116+
117+
expect(customFetch).toHaveBeenCalledOnce();
118+
expect(customFetch).toHaveBeenCalledWith(
119+
`https://${database}.bugsplat.com/post/js/`,
120+
expect.objectContaining({
121+
method: 'POST',
122+
body: fakeFormData,
123+
})
124+
);
125+
expect(globalFetchSpy).not.toHaveBeenCalled();
126+
});
127+
106128
it('should call fetch url containing database', async () => {
107129
fetchSpy.mockResolvedValue(fakeSuccessResponseBody);
108130

src/bugsplat.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ export function appendAttachment(body: FormData, attachment: BugSplatAttachment)
7676
*/
7777
export class BugSplat {
7878
private _formData = () => new FormData();
79+
private _fetch: typeof globalThis.fetch = globalThis.fetch.bind(globalThis);
7980

8081
private _appKey = '';
8182
private _attributes: Record<string, string> = {};
@@ -129,7 +130,7 @@ export class BugSplat {
129130
console.log('BugSplat Error:', errorToPost);
130131
console.log('BugSplat Url:', url);
131132

132-
const response = await globalThis.fetch(url, { method: 'POST', body });
133+
const response = await this._fetch(url, { method: 'POST', body });
133134
const json = await tryParseResponseJson(response);
134135

135136
console.log('BugSplat POST status code:', response.status);
@@ -208,7 +209,7 @@ export class BugSplat {
208209

209210
console.log('BugSplat Feedback:', title);
210211

211-
const response = await globalThis.fetch(baseUrl, { method: 'POST', body });
212+
const response = await this._fetch(baseUrl, { method: 'POST', body });
212213
const json = await tryParseResponseJson(response);
213214

214215
if (!response.ok) {

0 commit comments

Comments
 (0)