Move from browser-request to fetch (#23427)

This commit is contained in:
Michael Telatynski 2022-10-12 18:59:10 +01:00 committed by GitHub
parent 326a1a9056
commit 2ef6abbfb8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 169 additions and 148 deletions

View file

@ -41,6 +41,7 @@ import { RoomView as RoomViewClass } from 'matrix-react-sdk/src/components/struc
import LoginComponent from 'matrix-react-sdk/src/components/structures/auth/Login';
import WelcomeComponent from "matrix-react-sdk/src/components/views/auth/Welcome";
import EmbeddedPage from "matrix-react-sdk/src/components/structures/EmbeddedPage";
import { AutoDiscovery } from 'matrix-js-sdk/src/matrix';
const DEFAULT_HS_URL='http://my_server';
const DEFAULT_IS_URL='http://my_is';
@ -60,7 +61,7 @@ describe('loading:', function() {
beforeEach(function() {
httpBackend = new MockHttpBackend();
jssdk.request(httpBackend.requestFn);
window.fetch = httpBackend.fetchFn;
parentDiv = document.createElement('div');
// uncomment this to actually add the div to the UI, to help with
@ -73,21 +74,25 @@ describe('loading:', function() {
afterEach(async function() {
console.log(`${Date.now()}: loading: afterEach`);
if (parentDiv) {
ReactDOM.unmountComponentAtNode(parentDiv);
parentDiv.remove();
parentDiv = null;
try {
if (matrixChat) {
ReactDOM.unmountComponentAtNode(parentDiv);
parentDiv.remove();
parentDiv = null;
}
// unmounting should have cleared the MatrixClientPeg
expect(MatrixClientPeg.get()).toBe(null);
// clear the indexeddbs so we can start from a clean slate next time.
await Promise.all([
test_utils.deleteIndexedDB('matrix-js-sdk:crypto'),
test_utils.deleteIndexedDB('matrix-js-sdk:riot-web-sync'),
]);
cleanLocalstorage();
} catch (e) {
console.error(e);
}
// unmounting should have cleared the MatrixClientPeg
expect(MatrixClientPeg.get()).toBe(null);
// clear the indexeddbs so we can start from a clean slate next time.
await Promise.all([
test_utils.deleteIndexedDB('matrix-js-sdk:crypto'),
test_utils.deleteIndexedDB('matrix-js-sdk:riot-web-sync'),
]);
cleanLocalstorage();
console.log(`${Date.now()}: loading: afterEach complete`);
});
@ -421,7 +426,6 @@ describe('loading:', function() {
describe('Guest auto-registration:', function() {
it('shows a welcome page by default', function() {
loadApp();
return sleep(1).then(() => {

View file

@ -14,14 +14,13 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import request from 'browser-request';
import fetchMock from "fetch-mock-jest";
import { getVectorConfig } from "../../../src/vector/getconfig";
describe('getVectorConfig()', () => {
const setRequestMockImplementationOnce = (err?: unknown, response?: { status: number }, body?: string) =>
request.mockImplementationOnce((_opts, callback) => callback(err, response, body));
fetchMock.config.overwriteRoutes = true;
describe('getVectorConfig()', () => {
const prevDocumentDomain = document.domain;
const elementDomain = 'app.element.io';
const now = 1234567890;
@ -38,6 +37,7 @@ describe('getVectorConfig()', () => {
// stable value for cachebuster
jest.spyOn(Date, 'now').mockReturnValue(now);
jest.clearAllMocks();
fetchMock.mockClear();
});
afterAll(() => {
@ -46,85 +46,67 @@ describe('getVectorConfig()', () => {
});
it('requests specific config for document domain', async () => {
setRequestMockImplementationOnce(undefined, { status: 200 }, JSON.stringify(specificConfig))
setRequestMockImplementationOnce(undefined, { status: 200 }, JSON.stringify(generalConfig))
fetchMock.getOnce("express:/config.app.element.io.json", specificConfig);
fetchMock.getOnce("express:/config.json", generalConfig);
await getVectorConfig();
expect(request.mock.calls[0][0]).toEqual({ method: "GET", url: 'config.app.element.io.json', qs: { cachebuster: now } })
await expect(getVectorConfig()).resolves.toEqual(specificConfig);
});
it('adds trailing slash to relativeLocation when not an empty string', async () => {
setRequestMockImplementationOnce(undefined, { status: 200 }, JSON.stringify(specificConfig))
setRequestMockImplementationOnce(undefined, { status: 200 }, JSON.stringify(generalConfig))
fetchMock.getOnce("express:../config.app.element.io.json", specificConfig);
fetchMock.getOnce("express:../config.json", generalConfig);
await getVectorConfig('..');
expect(request.mock.calls[0][0]).toEqual(expect.objectContaining({ url: '../config.app.element.io.json' }))
expect(request.mock.calls[1][0]).toEqual(expect.objectContaining({ url: '../config.json' }))
});
it('returns parsed specific config when it is non-empty', async () => {
setRequestMockImplementationOnce(undefined, { status: 200 }, JSON.stringify(specificConfig))
setRequestMockImplementationOnce(undefined, { status: 200 }, JSON.stringify(generalConfig))
const result = await getVectorConfig();
expect(result).toEqual(specificConfig);
await expect(getVectorConfig("..")).resolves.toEqual(specificConfig);
});
it('returns general config when specific config succeeds but is empty', async () => {
setRequestMockImplementationOnce(undefined, { status: 200 }, JSON.stringify({}))
setRequestMockImplementationOnce(undefined, { status: 200 }, JSON.stringify(generalConfig))
fetchMock.getOnce("express:/config.app.element.io.json", {});
fetchMock.getOnce("express:/config.json", generalConfig);
const result = await getVectorConfig();
expect(result).toEqual(generalConfig);
await expect(getVectorConfig()).resolves.toEqual(generalConfig);
});
it('returns general config when specific config 404s', async () => {
setRequestMockImplementationOnce(undefined, { status: 404 })
setRequestMockImplementationOnce(undefined, { status: 200 }, JSON.stringify(generalConfig))
fetchMock.getOnce("express:/config.app.element.io.json", { status: 404 });
fetchMock.getOnce("express:/config.json", generalConfig);
const result = await getVectorConfig();
expect(result).toEqual(generalConfig);
await expect(getVectorConfig()).resolves.toEqual(generalConfig);
});
it('returns general config when specific config is fetched from a file and is empty', async () => {
setRequestMockImplementationOnce(undefined, { status: 0 }, '')
setRequestMockImplementationOnce(undefined, { status: 200 }, JSON.stringify(generalConfig))
fetchMock.getOnce("express:/config.app.element.io.json", 0);
fetchMock.getOnce("express:/config.json", generalConfig);
const result = await getVectorConfig();
expect(result).toEqual(generalConfig);
await expect(getVectorConfig()).resolves.toEqual(generalConfig);
});
it('returns general config when specific config returns a non-200 status', async () => {
setRequestMockImplementationOnce(undefined, { status: 401 })
setRequestMockImplementationOnce(undefined, { status: 200 }, JSON.stringify(generalConfig))
fetchMock.getOnce("express:/config.app.element.io.json", { status: 401 });
fetchMock.getOnce("express:/config.json", generalConfig);
const result = await getVectorConfig();
expect(result).toEqual(generalConfig);
await expect(getVectorConfig()).resolves.toEqual(generalConfig);
});
it('returns general config when specific config returns an error', async () => {
setRequestMockImplementationOnce('err1')
setRequestMockImplementationOnce(undefined, { status: 200 }, JSON.stringify(generalConfig))
fetchMock.getOnce("express:/config.app.element.io.json", { throws: "err1" });
fetchMock.getOnce("express:/config.json", generalConfig);
const result = await getVectorConfig();
expect(result).toEqual(generalConfig);
await expect(getVectorConfig()).resolves.toEqual(generalConfig);
});
it('rejects with an error when general config rejects', async () => {
setRequestMockImplementationOnce('err-specific');
setRequestMockImplementationOnce('err-general');
fetchMock.getOnce("express:/config.app.element.io.json", { throws: "err-specific" });
fetchMock.getOnce("express:/config.json", { throws: "err-general" });
await expect(() => getVectorConfig()).rejects.toEqual({"err": "err-general", "response": undefined});
await expect(getVectorConfig()).rejects.toBe("err-general");
});
it('rejects with an error when config is invalid JSON', async () => {
setRequestMockImplementationOnce('err-specific');
setRequestMockImplementationOnce(undefined, { status: 200 }, '{"invalid": "json",}');
fetchMock.getOnce("express:/config.app.element.io.json", { throws: "err-specific" });
fetchMock.getOnce("express:/config.json", '{"invalid": "json",}');
await expect(() => getVectorConfig()).rejects.toEqual({
err: new SyntaxError("Unexpected token } in JSON at position 19"),
});
// We can't assert it'll be a SyntaxError as node-fetch behaves differently
// https://github.com/wheresrhys/fetch-mock/issues/270
await expect(getVectorConfig()).rejects.toThrow("Unexpected token } in JSON at position 19");
});
});

View file

@ -14,12 +14,14 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
import request from 'browser-request';
import fetchMock from "fetch-mock-jest";
import { UpdateCheckStatus } from 'matrix-react-sdk/src/BasePlatform';
import { MatrixClientPeg } from 'matrix-react-sdk/src/MatrixClientPeg';
import WebPlatform from '../../../../src/vector/platform/WebPlatform';
fetchMock.config.overwriteRoutes = true;
describe('WebPlatform', () => {
beforeEach(() => {
jest.clearAllMocks();
@ -120,9 +122,6 @@ describe('WebPlatform', () => {
const envVersion = process.env.VERSION;
const prodVersion = '1.10.13';
const setRequestMockImplementation = (err?: unknown, response?: { status: number }, body?: string) =>
request.mockImplementation((_opts, callback) => callback(err, response, body));
beforeEach(() => {
jest.spyOn(MatrixClientPeg, 'userRegisteredWithinLastHours').mockReturnValue(false);
})
@ -157,7 +156,7 @@ describe('WebPlatform', () => {
describe('pollForUpdate()', () => {
it('should return not available and call showNoUpdate when current version matches most recent version', async () => {
process.env.VERSION = prodVersion;
setRequestMockImplementation(undefined, { status: 200}, prodVersion);
fetchMock.getOnce("/version", prodVersion);
const platform = new WebPlatform();
const showUpdate = jest.fn();
@ -171,7 +170,7 @@ describe('WebPlatform', () => {
it('should strip v prefix from versions before comparing', async () => {
process.env.VERSION = prodVersion;
setRequestMockImplementation(undefined, { status: 200}, `v${prodVersion}`);
fetchMock.getOnce("/version", `v${prodVersion}`);
const platform = new WebPlatform();
const showUpdate = jest.fn();
@ -186,7 +185,7 @@ describe('WebPlatform', () => {
it('should return ready and call showUpdate when current version differs from most recent version', async () => {
process.env.VERSION = '0.0.0'; // old version
setRequestMockImplementation(undefined, { status: 200}, prodVersion);
fetchMock.getOnce("/version", prodVersion);
const platform = new WebPlatform();
const showUpdate = jest.fn();
@ -201,7 +200,7 @@ describe('WebPlatform', () => {
it('should return ready without showing update when user registered in last 24', async () => {
process.env.VERSION = '0.0.0'; // old version
jest.spyOn(MatrixClientPeg, 'userRegisteredWithinLastHours').mockReturnValue(true);
setRequestMockImplementation(undefined, { status: 200}, prodVersion);
fetchMock.getOnce("/version", prodVersion);
const platform = new WebPlatform();
const showUpdate = jest.fn();
@ -214,7 +213,7 @@ describe('WebPlatform', () => {
});
it('should return error when version check fails', async () => {
setRequestMockImplementation('oups');
fetchMock.getOnce("/version", { throws: "oups" });
const platform = new WebPlatform();
const showUpdate = jest.fn();