From f7ddc2d89392aa52aaac1e5a40a281ad11d7936d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gon=C3=A7alo=20Morais?= Date: Mon, 14 Mar 2022 11:19:42 +0100 Subject: [PATCH] chore: add fetch example & test --- README.md | 14 ++++++++++- tests/unit/services/browser/window-test.ts | 27 ++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ea8e9798..8ea08df3 100644 --- a/README.md +++ b/README.md @@ -125,7 +125,10 @@ import { setupBrowserFakes } from 'ember-browser-services/test-support'; module('Scenario Name', function (hooks) { setupBrowserFakes(hooks, { - window: { location: { href: 'https://crowdstrike.com' } }, + window: { + location: { href: 'https://crowdstrike.com' }, + fetch: async (url) => ({ url }) + }, }); test('is at crowdstrike.com', function (assert) { @@ -133,6 +136,15 @@ module('Scenario Name', function (hooks) { assert.equal(service.location.href, 'https://crowdstrike.com'); // => succeeds }); + + test('fetches from crowdstrike.com', async function (assert) { + let service = this.owner.lookup('service:browser/window'); + let urlPath = 'crowdstrike.com'; + + let { url: urlUsed } = await service.fetch(urlPath); + + assert.equal(urlUsed, urlPath); + }); }); ``` diff --git a/tests/unit/services/browser/window-test.ts b/tests/unit/services/browser/window-test.ts index 92ab10aa..b8794733 100644 --- a/tests/unit/services/browser/window-test.ts +++ b/tests/unit/services/browser/window-test.ts @@ -13,6 +13,16 @@ module('Service | browser/window', function (hooks) { assert.strictEqual(service.location, window.location); assert.strictEqual(service.top.location, window.top?.location); assert.strictEqual(service.parent.location, window.parent.location); + + // we do some bind magic when we're dealing with functions, + // so this setup allows us to keep the same function for comparison + let bindBackup = window.fetch.bind; + window.fetch.bind = () => window.fetch; + + assert.strictEqual(service.fetch, window.fetch); + + // restore original `bind` + window.fetch.bind = bindBackup; }); }); @@ -29,6 +39,23 @@ module('Service | browser/window', function (hooks) { }); module('Examples', function () { + module('Stubbing fetch', function (hooks) { + setupBrowserFakes(hooks, { + window: { + fetch: async (url: string) => ({ url }), + }, + }); + + test('can intercept fetch', async function (assert) { + let service = this.owner.lookup('service:browser/window'); + let fakeUrl = 'https://example.com'; + let { url: urlUsed } = await service.fetch(fakeUrl); + + assert.equal(urlUsed, fakeUrl); + }); + }); + + module('Stubbing location.href', function (hooks) { setupBrowserFakes(hooks, { window: {