diff --git a/.gitignore b/.gitignore
index 15fd2e0..f3bfe15 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,6 +2,8 @@
deno/
deno-tests/
.gistrun/
+test/*.js
+test/*.d.ts
# Logs
logs
diff --git a/test/client.auth.spec.d.ts b/test/client.auth.spec.d.ts
deleted file mode 100644
index 8c47f03..0000000
--- a/test/client.auth.spec.d.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-///
-export {};
diff --git a/test/client.auth.spec.js b/test/client.auth.spec.js
deleted file mode 100644
index 41932a0..0000000
--- a/test/client.auth.spec.js
+++ /dev/null
@@ -1,214 +0,0 @@
-"use strict";
-///
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-const test_dtos_1 = require("./dtos/test.dtos");
-const chai = require("chai");
-const { expect, assert } = chai;
-const index_1 = require("../src/index");
-const TEST_URL = "https://test.servicestack.net";
-//const TEST_URL = "http://localhost:56500";
-const createJwt = (opt = {}) => {
- const request = Object.assign(new test_dtos_1.CreateJwt(), opt);
- if (!request.userAuthId)
- request.userAuthId = "1";
- if (!request.displayName)
- request.displayName = "test jwt";
- if (!request.email)
- request.email = "test@auth.com";
- return request;
-};
-//Clear existing User Session
-const clearSession = (client) => __awaiter(void 0, void 0, void 0, function* () {
- let logout = new test_dtos_1.Authenticate();
- logout.provider = "logout";
- yield client.post(logout);
-});
-const supportsServerEvents = () => typeof global.EventSource != "undefined";
-describe('JsonServiceClient Auth Tests', () => {
- let client;
- beforeEach(() => {
- client = new index_1.JsonServiceClient(TEST_URL);
- });
- it("Can auth with JWT", () => __awaiter(void 0, void 0, void 0, function* () {
- const request = createJwt();
- let response = yield client.post(request);
- client.bearerToken = response.token;
- let testAuth = yield client.get(new test_dtos_1.TestAuth());
- expect(testAuth.userId).eq("1");
- expect(testAuth.displayName).eq("test jwt");
- expect(testAuth.sessionId).not.empty;
- }));
- it("Does fire onAuthenticationRequired callback on 401", () => __awaiter(void 0, void 0, void 0, function* () {
- let count = 0;
- client.onAuthenticationRequired = () => {
- count++;
- return Promise.resolve(null);
- };
- try {
- yield client.get(new test_dtos_1.TestAuth());
- assert.fail("should throw");
- }
- catch (e) {
- let status = e.responseStatus;
- expect(status.errorCode).eq("401");
- expect(status.message).eq("Unauthorized");
- expect(count).eq(1);
- }
- }));
- it("Can use onAuthenticationRequired to auth client", () => __awaiter(void 0, void 0, void 0, function* () {
- let count = 0;
- client.onAuthenticationRequired = () => {
- count++;
- client.userName = "test";
- client.password = "test";
- return Promise.resolve(null);
- };
- let response = yield client.get(new test_dtos_1.TestAuth());
- expect(count).eq(1);
- }));
- it("Can use onAuthenticationRequired to fetch new token", () => __awaiter(void 0, void 0, void 0, function* () {
- let count = 0;
- client.onAuthenticationRequired = () => __awaiter(void 0, void 0, void 0, function* () {
- count++;
- let authClient = new index_1.JsonServiceClient(TEST_URL);
- authClient.userName = "test";
- authClient.password = "test";
- const response = yield authClient.get(new test_dtos_1.Authenticate());
- client.bearerToken = authClient.cookies['ss-tok'].value;
- });
- let response = yield client.get(new test_dtos_1.TestAuth());
- expect(count).eq(1);
- }));
- it("Can use onAuthenticationRequired to fetch new token after expired token", () => __awaiter(void 0, void 0, void 0, function* () {
- let count = 0;
- client.onAuthenticationRequired = () => __awaiter(void 0, void 0, void 0, function* () {
- count++;
- let createFreshJwt = createJwt();
- const freshJwt = yield client.post(createFreshJwt);
- client.bearerToken = freshJwt.token;
- });
- let createExpiredJwt = createJwt();
- createExpiredJwt.jwtExpiry = "2000-01-01";
- const expiredJwt = yield client.post(createExpiredJwt);
- client.bearerToken = expiredJwt.token;
- let response = yield client.get(new test_dtos_1.TestAuth());
- expect(count).eq(1);
- }));
- it("Can reauthenticate after an auto refresh access token", () => __awaiter(void 0, void 0, void 0, function* () {
- let client = new index_1.JsonServiceClient(TEST_URL);
- let auth = new test_dtos_1.Authenticate();
- auth.provider = "credentials";
- auth.userName = "test";
- auth.password = "test";
- let authResponse = yield client.post(auth);
- let refreshToken = authResponse.refreshToken;
- let createExpiredJwt = createJwt();
- createExpiredJwt.jwtExpiry = "2000-01-01";
- const expiredJwt = yield client.post(createExpiredJwt);
- let bearerToken = expiredJwt.token;
- yield clearSession(client);
- client = new index_1.JsonServiceClient(TEST_URL);
- client.bearerToken = bearerToken;
- client.refreshToken = refreshToken;
- auth.password = "notvalid";
- try {
- yield client.post(auth);
- assert.fail("should throw");
- }
- catch (e) {
- let status = e.responseStatus;
- expect(status.errorCode).eq("Unauthorized");
- expect(status.message).eq("Invalid Username or Password");
- }
- }));
- it('Does fetch AccessToken using RefreshTokenCookies', () => __awaiter(void 0, void 0, void 0, function* () {
- let client = new index_1.JsonServiceClient(TEST_URL);
- let authResponse = yield client.post(new test_dtos_1.Authenticate({
- provider: "credentials",
- userName: "test",
- password: "test"
- }));
- expect(client.useTokenCookie).eq(true);
- let request = new test_dtos_1.Secured({ name: "test" });
- let response = yield client.post(request);
- expect(response.result).eq(request.name);
- yield client.post(new test_dtos_1.InvalidateLastAccessToken());
- response = yield client.post(request);
- expect(response.result).eq(request.name);
- }));
- it("Invalid RefreshToken throws RefreshTokenException ErrorResponse", () => __awaiter(void 0, void 0, void 0, function* () {
- let client = new index_1.JsonServiceClient(TEST_URL);
- client.refreshToken = "Invalid.Refresh.Token";
- try {
- let response = yield client.get(new test_dtos_1.TestAuth());
- assert.fail("should throw");
- }
- catch (e) {
- expect(e.type).eq("RefreshTokenException");
- expect(e.responseStatus.errorCode).eq("ArgumentException");
- expect(e.responseStatus.message).eq("Illegal base64url string!");
- }
- }));
- it("Expires RefreshToken throws RefreshTokenException", () => __awaiter(void 0, void 0, void 0, function* () {
- let client = new index_1.JsonServiceClient(TEST_URL);
- let createExpiredJwt = new test_dtos_1.CreateRefreshJwt();
- createExpiredJwt.jwtExpiry = "2000-01-01";
- const expiredJwt = yield client.post(createExpiredJwt);
- client.refreshToken = expiredJwt.token;
- try {
- let response = yield client.get(new test_dtos_1.TestAuth());
- assert.fail("should throw");
- }
- catch (e) {
- expect(e.type).eq("RefreshTokenException");
- expect(e.responseStatus.errorCode).eq("TokenException");
- expect(e.responseStatus.message).eq("Token has expired");
- }
- }));
- it("Can authenticate with ServerEvents using JWT", done => {
- (() => __awaiter(void 0, void 0, void 0, function* () {
- if (!supportsServerEvents())
- return done();
- let authClient = new index_1.JsonServiceClient(TEST_URL);
- const request = createJwt();
- let response = yield authClient.post(request);
- // Alternatives for browsers is to convert the JWT to a cookie so it's sent in future HTTP requests
- // a) Typed API
- // let client = new JsonServiceClient(TEST_URL);
- // client.setBearerToken(response.token);
- // await client.post(new dtos.ConvertSessionToToken());
- // b) Using fetch directly without types
- // let headers = new Headers();
- // headers.set("Authorization", "Bearer " + response.token);
- // await fetch(TEST_URL + "/session-to-token",
- // { method:"POST", headers, credentials:"include" });
- // Remote Server needs `new JwtAuthProvider { AllowInQueryString = true }`
- let sseClient = new index_1.ServerEventsClient(TEST_URL, ["*"], {
- // Works in both browers + node.exe server apps
- resolveStreamUrl: url => (0, index_1.appendQueryString)(url, { "ss-tok": response.token }),
- handlers: {
- onConnect: (e => {
- sseClient.stop();
- done();
- })
- },
- onException: (e) => {
- expect(JSON.stringify(e)).null;
- },
- });
- // c) also works in browsers:
- // sseClient.serviceClient.setBearerToken(response.token);
- // await sseClient.serviceClient.post(new dtos.ConvertSessionToToken());
- sseClient.start();
- }))();
- });
-});
diff --git a/test/client.spec.d.ts b/test/client.spec.d.ts
deleted file mode 100644
index 8c47f03..0000000
--- a/test/client.spec.d.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-///
-export {};
diff --git a/test/client.spec.js b/test/client.spec.js
deleted file mode 100644
index 32d5431..0000000
--- a/test/client.spec.js
+++ /dev/null
@@ -1,318 +0,0 @@
-"use strict";
-///
-//import 'cross-fetch/polyfill'
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-const dtos = require("./dtos/techstacks.dtos");
-const test_dtos_1 = require("./dtos/test.dtos");
-const chai = require("chai");
-const index_1 = require("../src/index");
-const { expect, assert } = chai;
-const TECHSTACKS_URL = "https://techstacks.io";
-const TEST_URL = "https://test.servicestack.net";
-//Clear existing User Session
-const clearSession = (client) => __awaiter(void 0, void 0, void 0, function* () {
- let logout = new test_dtos_1.Authenticate({ provider: "logout" });
- yield client.post(logout);
-});
-describe('JsonServiceClient Tests', () => {
- let client;
- let testClient;
- beforeEach(() => {
- client = new index_1.JsonServiceClient(TECHSTACKS_URL);
- testClient = new index_1.JsonServiceClient(TEST_URL);
- });
- it('Should get techs response', () => __awaiter(void 0, void 0, void 0, function* () {
- const api = yield client.api(new dtos.GetAllTechnologies());
- expect(api.response.results.length).to.be.greaterThan(0);
- expect(api.completed).eq(true);
- expect(api.succeeded).eq(true);
- expect(api.failed).eq(false);
- }));
- it('Can get multiple responses', () => __awaiter(void 0, void 0, void 0, function* () {
- var _a;
- let requests = [
- new dtos.AppOverview(),
- new dtos.DeleteTechnology(),
- new dtos.GetAllTechnologies(),
- new dtos.GetAllTechnologyStacks(),
- ];
- let results = yield Promise.all(requests.map((request) => __awaiter(void 0, void 0, void 0, function* () { return ({ request, api: yield client.api(request) }); })));
- let failed = results.filter(x => x.api.failed);
- console.log(`${failed.length} failed`);
- failed.forEach(x => console.log(` ${x.request.getTypeName()} Request Failed: ${failed.map(x => x.api.errorMessage)}`));
- let succeeded = results.filter(x => x.api.succeeded);
- console.log(`\n${succeeded.length} succeeded: ${succeeded.map(x => x.request.getTypeName()).join(', ')}`);
- let r = (_a = succeeded.find(x => x.request.getTypeName() == 'AppOverview')) === null || _a === void 0 ? void 0 : _a.api.response;
- if (r)
- console.log(`Top 5 Technologies: ${r.topTechnologies.slice(0, 4).map(tech => tech.name).join(', ')}`);
- }));
- it('Should get techstacks overview', () => __awaiter(void 0, void 0, void 0, function* () {
- const api = yield client.api(new dtos.Overview());
- expect(api.response.topTechnologies.length).to.be.greaterThan(0);
- }));
- it('Should throw 405', () => __awaiter(void 0, void 0, void 0, function* () {
- const testClient = new index_1.JsonServiceClient(TEST_URL);
- const api = yield testClient.api(new dtos.Overview());
- expect(api.errorCode).to.be.equal('NotImplementedException');
- expect(api.errorMessage).to.be.equal('The operation does not exist for this service');
- }));
- it('Should throw 401', () => __awaiter(void 0, void 0, void 0, function* () {
- const api = yield client.api(new dtos.CreateTechnology());
- expect(api.errorCode).to.equal("401");
- // nginx reverse proxy might be stripping this, can't reproduce locally or in docker
- // expect(api.errorMessage).to.equal('Unauthorized')
- }));
- it('Should generate default value', () => {
- const request = new test_dtos_1.HelloTypes({ bool: false, int: 0 });
- const requestUrl = (0, index_1.appendQueryString)(TEST_URL, request);
- expect(requestUrl).to.equal(TEST_URL + "?bool=false&int=0");
- });
- it('Should return raw text', () => __awaiter(void 0, void 0, void 0, function* () {
- const request = new test_dtos_1.ReturnString({ data: "0x10" });
- const str = yield testClient.get(request);
- expect(str).eq("0x10");
- }));
- // node-fetch v2 will implement arrayBuffer: https://github.com/bitinn/node-fetch/issues/51#issuecomment-253998195
- // it ('Should return raw bytes', done => {
- // var request = new ReturnBytes()
- // request.data = new Uint8Array([0x01])
- // testClient.get(request)
- // .then(r => {
- // console.log('r',r)
- // expect(r[0]).to.equal(0x01)
- // done()
- // }, done)
- // })
- it('Can authenticate with HTTP Basic Auth', () => __awaiter(void 0, void 0, void 0, function* () {
- testClient.userName = "test";
- testClient.password = "test";
- const api = yield testClient.api(new test_dtos_1.TestAuth());
- expect(api.response.userName).to.equal("test");
- }));
- it('Can authenticate with Credentials', () => __awaiter(void 0, void 0, void 0, function* () {
- yield clearSession(testClient);
- const request = new test_dtos_1.Authenticate({
- provider: "credentials",
- userName: "test",
- password: "test",
- rememberMe: true
- });
- let authResponse = yield testClient.post(request);
- expect(authResponse.userId).not.empty;
- expect(authResponse.sessionId).not.empty;
- //authenticated request
- const api = yield testClient.api(new test_dtos_1.TestAuth());
- console.log(api);
- expect(api.response.userName).to.equal("test");
- yield clearSession(testClient);
- }));
- // Test needs review due to httponly nature of jwt token cookies.
- // it ('Can authenticate with BearerToken', async () => {
- // const request = new Authenticate({
- // provider: "credentials",
- // userName: "test",
- // password: "test",
- // })
- // let authApi = await testClient.api(request)
- // expect(authApi.succeeded)
- // const jwtToken = testClient.cookies['ss-tok'].value
- // expect(jwtToken).not.empty
- //
- // //Clear existing User Session
- // const logout = new Authenticate({ provider: "logout" })
- // await testClient.api(logout)
- //
- // const newClient = new JsonServiceClient(TEST_URL)
- //
- // let api = await newClient.api(new Authenticate())
- //
- // expect(api.errorCode).to.equal("401")
- // expect(api.errorMessage).to.equal("Unauthorized")
- //
- // //New Client with BearerToken
- // newClient.bearerToken = jwtToken
- // api = await newClient.api(new Authenticate())
- // expect(api.response.userId).not.empty
- // expect(api.response.sessionId).not.empty
- // })
- it('Should return 401 for failed HTTP Basic Auth requests', () => __awaiter(void 0, void 0, void 0, function* () {
- testClient.userName = "test";
- testClient.password = "wrong";
- testClient.exceptionFilter = (res, error) => {
- expect(error.responseStatus.errorCode).to.be.equal('Unauthorized');
- expect(error.responseStatus.message).to.be.equal('Invalid Username or Password');
- };
- const api = yield testClient.api(new test_dtos_1.TestAuth());
- expect(api.errorCode).to.be.equal('Unauthorized');
- expect(api.errorMessage).to.be.equal('Invalid Username or Password');
- }));
- it('Should return 401 for failed Auth requests (blazor-vue)', () => __awaiter(void 0, void 0, void 0, function* () {
- const client = new index_1.JsonServiceClient("https://blazor-vue.web-templates.io");
- client.exceptionFilter = (res, error) => {
- expect(error.responseStatus.errorCode).to.be.equal('Unauthorized');
- expect(error.responseStatus.message).to.be.equal('Invalid Username or Password');
- };
- const api = yield client.api(new test_dtos_1.Authenticate({
- provider: "credentials",
- userName: "test",
- password: "wrong",
- }));
- if (typeof process != "undefined")
- process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
- expect(api.errorCode).to.be.equal('Unauthorized');
- expect(api.errorMessage).to.be.equal('Invalid Username or Password');
- if (typeof process != "undefined")
- process.env.NODE_TLS_REJECT_UNAUTHORIZED = 1;
- }));
- it('Should return 401 for failed Auth requests (Test)', () => __awaiter(void 0, void 0, void 0, function* () {
- testClient.exceptionFilter = (res, error) => {
- expect(error.responseStatus.errorCode).to.be.equal('Unauthorized');
- expect(error.responseStatus.message).to.be.equal('Invalid Username or Password');
- };
- const api = yield testClient.api(new test_dtos_1.Authenticate({
- provider: "credentials",
- userName: "test",
- password: "wrong",
- }));
- expect(api.errorCode).to.be.equal('Unauthorized');
- expect(api.errorMessage).to.be.equal('Invalid Username or Password');
- }));
- it('Can POST to EchoTypes', () => __awaiter(void 0, void 0, void 0, function* () {
- const request = new test_dtos_1.EchoTypes({ int: 1, string: 'foo' });
- const api = yield testClient.api(request);
- expect(api.response.int).to.equal(request.int);
- expect(api.response.string).to.equal(request.string);
- }));
- it('Can GET IReturnVoid requests', () => __awaiter(void 0, void 0, void 0, function* () {
- let api = yield testClient.apiVoid(new test_dtos_1.HelloReturnVoid({ id: 1 }), 'GET');
- expect(api.completed).eq(true);
- expect(api.succeeded).eq(true);
- expect(api.failed).eq(false);
- }));
- it('Can POST IReturnVoid requests', () => __awaiter(void 0, void 0, void 0, function* () {
- let api = yield testClient.apiVoid(new test_dtos_1.HelloReturnVoid({ id: 1 }));
- expect(api.completed).eq(true);
- expect(api.succeeded).eq(true);
- expect(api.failed).eq(false);
- }));
- it('Can handle Validation Errors with Camel Casing', () => __awaiter(void 0, void 0, void 0, function* () {
- testClient.requestFilter = req => req.url += "?jsconfig=EmitCamelCaseNames:true";
- const api = yield testClient.api(new test_dtos_1.ThrowValidation());
- expect(api.errorCode).to.be.equal("InclusiveBetween");
- expect(api.errorMessage).to.be.equal("'Age' must be between 1 and 120. You entered 0.");
- expect(api.errors.length).to.be.equal(3);
- expect(api.errors[1].errorCode).to.be.equal("NotEmpty");
- expect(api.errors[1].fieldName).to.be.equal("Required");
- expect(api.errors[1].message).to.be.equal("'Required' must not be empty.");
- }));
- it('Can handle Validation Errors with Pascal Casing', () => __awaiter(void 0, void 0, void 0, function* () {
- testClient.requestFilter = req => req.url += "?jsconfig=EmitCamelCaseNames:false";
- const api = yield testClient.api(new test_dtos_1.ThrowValidation());
- expect(api.errorCode).to.be.equal("InclusiveBetween");
- expect(api.errorMessage).to.be.equal("'Age' must be between 1 and 120. You entered 0.");
- expect(api.errors.length).to.be.equal(3);
- expect(api.errors[1].errorCode).to.be.equal("NotEmpty");
- expect(api.errors[1].fieldName).to.be.equal("Required");
- expect(api.errors[1].message).to.be.equal("'Required' must not be empty.");
- }));
- it('Can GET using only path info', () => __awaiter(void 0, void 0, void 0, function* () {
- const r = yield testClient.get("/hello/World");
- expect(r.result).to.equal("Hello, World!");
- }));
- it('Can GET using absolute url', () => __awaiter(void 0, void 0, void 0, function* () {
- const r = yield testClient.get("https://test.servicestack.net/hello/World");
- expect(r.result).to.equal("Hello, World!");
- }));
- it('Can GET using route and queryString', () => __awaiter(void 0, void 0, void 0, function* () {
- const r = yield testClient.get("/hello", { name: "World" });
- expect(r.result).to.equal("Hello, World!");
- }));
- it('Can GET EchoTypes using route and interface', () => __awaiter(void 0, void 0, void 0, function* () {
- const request = { int: 1, string: "foo" };
- const r = yield testClient.get("/echo/types", request);
- expect(r.int).to.equal(request.int);
- expect(r.string).to.equal(request.string);
- }));
- it('Can query AutoQuery with runtime args', () => __awaiter(void 0, void 0, void 0, function* () {
- let request = new dtos.FindTechnologies({ take: 3 });
- let r = yield client.api(request, { VendorName: "Amazon" });
- expect(r.response.results.length).to.equal(3);
- expect(r.response.results.map(x => x.vendorName)).to.have.members(["Amazon", "Amazon", "Amazon"]);
- }));
- it('Can query AutoQuery with anon object and runtime args', () => __awaiter(void 0, void 0, void 0, function* () {
- let request = { Take: 3, VendorName: "Amazon" };
- let r = yield client.get("/technology/search", request);
- expect(r.results.length).to.equal(3);
- expect(r.results.map(x => x.vendorName)).to.have.members(["Amazon", "Amazon", "Amazon"]);
- }));
- it('Can send raw JSON as object', () => __awaiter(void 0, void 0, void 0, function* () {
- let body = { foo: "bar" };
- let request = new test_dtos_1.SendJson({ id: 1, name: "name" });
- const testClient = new index_1.JsonServiceClient(TEST_URL);
- if (typeof document == "undefined") //fetch in browser ignores custom headers
- testClient.responseFilter = res => expect(res.headers.get("X-Args")).to.eq("1,name");
- const json = yield testClient.postBody(request, body);
- const obj = JSON.parse(json);
- expect(obj["foo"]).to.eq("bar");
- }));
- it('Can send raw JSON as string', () => __awaiter(void 0, void 0, void 0, function* () {
- let body = { foo: "bar" };
- let request = new test_dtos_1.SendJson({ id: 1, name: "name" });
- const testClient = new index_1.JsonServiceClient(TEST_URL);
- if (typeof document == "undefined") //fetch in browser ignores custom headers
- testClient.responseFilter = res => expect(res.headers.get("X-Args")).to.eq("1,name");
- const json = yield testClient.postBody(request, JSON.stringify(body));
- const obj = JSON.parse(json);
- expect(obj["foo"]).to.eq("bar");
- }));
- it('Can send raw string', () => __awaiter(void 0, void 0, void 0, function* () {
- let body = { foo: "bar" };
- let request = new test_dtos_1.SendText({ id: 1, name: "name", contentType: "text/plain" });
- const testClient = new index_1.JsonServiceClient(TEST_URL);
- if (typeof document == "undefined") //fetch in browser ignores custom headers
- testClient.responseFilter = res => expect(res.headers.get("X-Args")).to.eq("1,name");
- const str = yield testClient.postBody(request, "foo");
- expect(str).to.eq("foo");
- }));
- it('Can sendAll batch request', () => __awaiter(void 0, void 0, void 0, function* () {
- const requests = ["foo", "bar", "baz"].map(name => Object.assign(new test_dtos_1.Hello(), { name }));
- testClient.urlFilter = url => expect(url).eq(TEST_URL + "/api/Hello[]");
- const responses = yield testClient.sendAll(requests);
- expect(responses.map(x => x.result)).deep.equals(['Hello, foo!', 'Hello, bar!', 'Hello, baz!']);
- testClient.urlFilter = null;
- }));
- it('Can sendAllOneWay IReturn batch request', () => __awaiter(void 0, void 0, void 0, function* () {
- const requests = ["foo", "bar", "baz"].map(name => Object.assign(new test_dtos_1.Hello(), { name }));
- testClient.urlFilter = url => expect(url).eq(TEST_URL + "/api/Hello[]");
- const response = yield testClient.sendAllOneWay(requests);
- expect(response).to.undefined;
- testClient.urlFilter = null;
- }));
- it('Can sendAllOneWay IReturnVoid batch request', () => __awaiter(void 0, void 0, void 0, function* () {
- const requests = ["foo", "bar", "baz"].map(name => Object.assign(new test_dtos_1.HelloReturnVoid(), { name }));
- testClient.urlFilter = url => expect(url).eq(TEST_URL + "/api/HelloReturnVoid[]");
- const response = yield testClient.sendAllOneWay(requests);
- expect(response).to.undefined;
- testClient.urlFilter = null;
- }));
- it('Should change base path', () => {
- let client = new index_1.JsonServiceClient('https://test.servicestack.net/');
- expect(client.replyBaseUrl).to.eq('https://test.servicestack.net/api/');
- expect(client.oneWayBaseUrl).to.eq('https://test.servicestack.net/api/');
- client.basePath = null;
- expect(client.replyBaseUrl).to.eq('https://test.servicestack.net/json/reply/');
- expect(client.oneWayBaseUrl).to.eq('https://test.servicestack.net/json/oneway/');
- client.basePath = 'api';
- expect(client.replyBaseUrl).to.eq('https://test.servicestack.net/api/');
- expect(client.oneWayBaseUrl).to.eq('https://test.servicestack.net/api/');
- });
-});
diff --git a/test/inspect.spec.d.ts b/test/inspect.spec.d.ts
deleted file mode 100644
index cb0ff5c..0000000
--- a/test/inspect.spec.d.ts
+++ /dev/null
@@ -1 +0,0 @@
-export {};
diff --git a/test/inspect.spec.js b/test/inspect.spec.js
deleted file mode 100644
index 452e855..0000000
--- a/test/inspect.spec.js
+++ /dev/null
@@ -1,35 +0,0 @@
-"use strict";
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-const chai = require("chai");
-const { expect, assert } = chai;
-const index_1 = require("../src/index");
-describe('Inspect Tests', () => {
- it('Can use Inspect', () => __awaiter(void 0, void 0, void 0, function* () {
- let orgName = "nodejs";
- let orgRepos = (yield (yield fetch(`https://api.github.com/orgs/${orgName}/repos`)).json())
- .map(x => ({
- name: x.name,
- description: x.description,
- lang: x.language,
- watchers: x.watchers_count,
- forks: x.forks
- }));
- orgRepos.sort((a, b) => b.watchers - a.watchers);
- console.log(`Top 3 ${orgName} Github Repos:`);
- index_1.Inspect.printDump(orgRepos.slice(0, 3));
- console.log(`\nTop 10 ${orgName} Github Repos:`);
- index_1.Inspect.printDumpTable(orgRepos.map(x => ({
- name: x.name, lang: x.lang, watchers: x.watchers, forks: x.forks
- })).slice(0, 10));
- index_1.Inspect.vars({ orgRepos });
- }));
-});
diff --git a/test/issues.spec.d.ts b/test/issues.spec.d.ts
deleted file mode 100644
index 145c66d..0000000
--- a/test/issues.spec.d.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-export interface IReturn {
- createResponse(): T;
-}
-export interface IReturnVoid {
- createResponse(): void;
-}
-export declare class ResponseError {
- errorCode: string;
- fieldName: string;
- message: string;
- meta: {
- [index: string]: string;
- };
-}
-export declare class ResponseStatus {
- errorCode: string;
- message: string;
- stackTrace: string;
- errors: ResponseError[];
- meta: {
- [index: string]: string;
- };
-}
-export declare class GetProducts implements IReturn> {
- id: string;
- createResponse(): ResponseBase;
- getTypeName(): string;
-}
-export declare class ResponseBase {
- responseStatus: ResponseStatus;
- result: T;
- results: T[];
- total: number;
-}
-export declare class ProductDto implements IReturn> {
- id: string;
- createResponse(): ResponseBase;
- getTypeName(): string;
-}
diff --git a/test/issues.spec.js b/test/issues.spec.js
deleted file mode 100644
index 83f4c11..0000000
--- a/test/issues.spec.js
+++ /dev/null
@@ -1,39 +0,0 @@
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.ProductDto = exports.ResponseBase = exports.GetProducts = exports.ResponseStatus = exports.ResponseError = void 0;
-const chai = require("chai");
-const { expect, assert } = chai;
-const index_1 = require("../src/index");
-describe('Issues', () => {
- it('Does generate URL', done => {
- let dtoName = (0, index_1.nameOf)(new GetProducts());
- expect(dtoName).eq('GetProducts');
- done();
- });
-});
-// @DataContract
-class ResponseError {
-}
-exports.ResponseError = ResponseError;
-// @DataContract
-class ResponseStatus {
-}
-exports.ResponseStatus = ResponseStatus;
-// @Route("/settings/products", "GET")
-// @Route("/settings/products/{Id}", "GET")
-class GetProducts {
- createResponse() { return new ResponseBase(); }
- getTypeName() { return "GetProducts"; }
-}
-exports.GetProducts = GetProducts;
-class ResponseBase {
-}
-exports.ResponseBase = ResponseBase;
-// @Route("/settings/products", "POST")
-// @Route("/settings/products/{Id}", "PUT")
-class ProductDto {
- // more...
- createResponse() { return new ResponseBase(); }
- getTypeName() { return "GetProducts"; }
-}
-exports.ProductDto = ProductDto;
diff --git a/test/jsv.spec.d.ts b/test/jsv.spec.d.ts
deleted file mode 100644
index cb0ff5c..0000000
--- a/test/jsv.spec.d.ts
+++ /dev/null
@@ -1 +0,0 @@
-export {};
diff --git a/test/jsv.spec.js b/test/jsv.spec.js
deleted file mode 100644
index 8d60b4a..0000000
--- a/test/jsv.spec.js
+++ /dev/null
@@ -1,14 +0,0 @@
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-const chai = require("chai");
-const { expect, assert } = chai;
-const index_1 = require("../src/index");
-describe('JSV Tests', () => {
- it('Can serialize to JSV', () => {
- expect(index_1.JSV.stringify({ Key: "Value" })).eq('{Key:Value}');
- expect(index_1.JSV.stringify({ Id: 1234, Name: "TEST", Obj: [{ Id: 1, Key: "Value" }] })).eq('{Id:1234,Name:TEST,Obj:[{Id:1,Key:Value}]}');
- expect(index_1.JSV.stringify({ Float: 1.1, Double: 2.2, Decimal: 3.3 })).eq('{Float:1.1,Double:2.2,Decimal:3.3}');
- expect(index_1.JSV.stringify("https://url.com")).eq('"https://url.com"');
- expect(index_1.JSV.stringify("1,2,3")).eq('"1,2,3"');
- });
-});
diff --git a/test/receivers.d.ts b/test/receivers.d.ts
deleted file mode 100644
index 90c5aba..0000000
--- a/test/receivers.d.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { ServerEventMessage, ServerEventReceiver } from '../src/index';
-import { ChatMessage, CustomType, SetterType } from './dtos/test.dtos';
-export declare class TestNamedReceiver {
- static FooMethodReceived: CustomType;
- static BarMethodReceived: CustomType;
- static NoSuchMethodReceived: CustomType;
- static NoSuchMethodSelector: string;
- static QuxSetterReceived: CustomType;
- get quxSetter(): CustomType;
- set quxSetter(value: CustomType);
- fooMethod(request: CustomType): void;
- barMethod(request: CustomType): CustomType;
- noSuchMethod(selector: string, message: ServerEventMessage): void;
-}
-export declare class TestGlobalReceiver {
- static CustomTypeMethodReceived: CustomType;
- static NoSuchMethodReceived: CustomType;
- static NoSuchMethodSelector: string;
- static SetterTypeReceived: SetterType;
- set SetterType(value: SetterType);
- CustomType(request: CustomType): CustomType;
- noSuchMethod(selector: string, message: ServerEventMessage): void;
-}
-export declare class TestJavaScriptReceiver extends ServerEventReceiver {
- static ChatReceived: ChatMessage;
- static AnnounceReceived: string;
- AnnounceInstance: string;
- static ToggleReceived: string;
- static ToggleRequestReceived: ServerEventMessage;
- static BackgroundImageReceived: string;
- static BackgroundImageRequestReceived: ServerEventMessage;
- chat(request: ChatMessage): void;
- announce(message: string): void;
- toggle(message: string): void;
- backgroundImage(message: string): void;
-}
diff --git a/test/receivers.js b/test/receivers.js
deleted file mode 100644
index 56ce8f5..0000000
--- a/test/receivers.js
+++ /dev/null
@@ -1,61 +0,0 @@
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.TestJavaScriptReceiver = exports.TestGlobalReceiver = exports.TestNamedReceiver = void 0;
-const index_1 = require("../src/index");
-class TestNamedReceiver {
- get quxSetter() { return TestNamedReceiver.QuxSetterReceived; }
- set quxSetter(value) {
- TestNamedReceiver.QuxSetterReceived = value;
- }
- fooMethod(request) {
- TestNamedReceiver.FooMethodReceived = request;
- }
- barMethod(request) {
- TestNamedReceiver.BarMethodReceived = request;
- return request;
- }
- noSuchMethod(selector, message) {
- var msg = message;
- try {
- TestNamedReceiver.NoSuchMethodReceived = JSON.parse(message.json);
- TestNamedReceiver.NoSuchMethodSelector = selector;
- }
- catch (e) {
- console.log('ERROR TestNamedReceiver:', message.json);
- }
- }
-}
-exports.TestNamedReceiver = TestNamedReceiver;
-class TestGlobalReceiver {
- set SetterType(value) {
- TestGlobalReceiver.SetterTypeReceived = value;
- }
- CustomType(request) {
- TestGlobalReceiver.CustomTypeMethodReceived = request;
- return request;
- }
- noSuchMethod(selector, message) {
- var msg = message;
- TestGlobalReceiver.NoSuchMethodReceived = JSON.parse(message.json);
- TestGlobalReceiver.NoSuchMethodSelector = selector;
- }
-}
-exports.TestGlobalReceiver = TestGlobalReceiver;
-class TestJavaScriptReceiver extends index_1.ServerEventReceiver {
- chat(request) {
- TestJavaScriptReceiver.ChatReceived = request;
- }
- announce(message) {
- TestJavaScriptReceiver.AnnounceReceived = message;
- this.AnnounceInstance = message;
- }
- toggle(message) {
- TestJavaScriptReceiver.ToggleReceived = message;
- TestJavaScriptReceiver.ToggleRequestReceived = this.request;
- }
- backgroundImage(message) {
- TestJavaScriptReceiver.BackgroundImageReceived = message;
- TestJavaScriptReceiver.BackgroundImageRequestReceived = this.request;
- }
-}
-exports.TestJavaScriptReceiver = TestJavaScriptReceiver;
diff --git a/test/serialization.spec.d.ts b/test/serialization.spec.d.ts
deleted file mode 100644
index cb0ff5c..0000000
--- a/test/serialization.spec.d.ts
+++ /dev/null
@@ -1 +0,0 @@
-export {};
diff --git a/test/serialization.spec.js b/test/serialization.spec.js
deleted file mode 100644
index 6dfd7d9..0000000
--- a/test/serialization.spec.js
+++ /dev/null
@@ -1,160 +0,0 @@
-"use strict";
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-const chai = require("chai");
-const { expect, assert } = chai;
-const test_dtos_1 = require("./dtos/test.dtos");
-const index_1 = require("../src/index");
-function createPoco(name) {
- return new test_dtos_1.Poco({ name: name });
-}
-function createAllCollectionTypes() {
- return new test_dtos_1.AllCollectionTypes({
- intArray: [
- 1,
- 2,
- 3
- ], intList: [
- 4,
- 5,
- 6
- ], stringArray: [
- "A",
- "B",
- "C"
- ], stringList: [
- "D",
- "E",
- "F"
- ], byteArray: (0, index_1.toBase64String)("ABC"),
- pocoArray: [
- createPoco("pocoArray")
- ], pocoList: [
- createPoco("pocoList")
- ], pocoLookup: {
- "A": [createPoco("B"), createPoco("C")]
- }, pocoLookupMap: {
- "A": [
- { "B": createPoco("C"), "D": createPoco("E") }
- ]
- }
- });
-}
-function createHelloAllTypes() {
- return new test_dtos_1.HelloAllTypes({
- name: "name",
- allTypes: createAllTypes(),
- allCollectionTypes: createAllCollectionTypes()
- });
-}
-function createAllTypes() {
- return new test_dtos_1.AllTypes({
- id: 1,
- char: 'c',
- byte: 2,
- short: 3,
- int: 4,
- long: 5,
- uShort: 6,
- uInt: 7,
- uLong: 8,
- float: 1.1,
- double: 2.2,
- decimal: 3.0,
- string: "string",
- dateTime: (0, index_1.toDateTime)(new Date(Date.UTC(2001, 0, 1))),
- dateTimeOffset: (0, index_1.toDateTime)(new Date(Date.UTC(2001, 0, 1))),
- timeSpan: "PT1H",
- guid: "ea762009b66c410b9bf5ce21ad519249",
- stringList: ["A", "B", "C"],
- stringArray: ["D", "E", "F"],
- stringMap: {
- "A": "D",
- "B": "E",
- "C": "F",
- },
- intStringMap: { 1: "A", 2: "B", 3: "C" },
- subType: new test_dtos_1.SubType({ id: 1, name: "name" })
- });
-}
-function assertHelloAllTypesResponse(dto) {
- expect(dto.result).equals("name");
- assertAllTypes(dto.allTypes);
- assertAllCollectionTypes(dto.allCollectionTypes);
-}
-function assertAllTypes(dto) {
- expect(dto.id).equals(1);
- expect(dto.byte).equals(2);
- expect(dto.short).equals(3);
- expect(dto.int).equals(4);
- expect(dto.uShort).equals(6);
- expect(dto.uInt).equals(7);
- expect(dto.uLong).equals(8);
- expect(dto.float).equals(1.1);
- expect(dto.double).equals(2.2);
- expect(dto.decimal).equals(3.0);
- expect(dto.string).equals("string");
- expect(dto.dateTime).equals("/Date(978307200000)/");
- expect(dto.dateTimeOffset).equals("/Date(978307200000)/");
- expect(dto.timeSpan).equals("PT1H");
- expect(dto.guid).equals("ea762009b66c410b9bf5ce21ad519249");
- expect(dto.stringList).deep.equals(["A", "B", "C"]);
- expect(dto.stringArray).deep.equals(["D", "E", "F"]);
- expect(dto.stringMap).deep.equals({
- "A": "D",
- "B": "E",
- "C": "F",
- });
- expect(dto.intStringMap).deep.equals({ 1: "A", 2: "B", 3: "C" });
- expect(dto.subType.id).equals(1);
- expect(dto.subType.name).equals("name");
-}
-function assertAllCollectionTypes(dto) {
- expect(dto.intArray).deep.equals([1, 2, 3]);
- expect(dto.intList).deep.equals([4, 5, 6]);
- expect(dto.stringArray).deep.equals(["A", "B", "C"]);
- expect(dto.stringList).deep.equals(["D", "E", "F"]);
- expect(dto.byteArray).equals((0, index_1.toBase64String)("ABC"));
- expect(dto.pocoArray.length).equals(1);
- expect(dto.pocoArray[0].name).equals("pocoArray");
- expect(dto.pocoList.length).equals(1);
- expect(dto.pocoList[0].name).equals("pocoList");
- expect(Object.keys(dto.pocoLookup).length).equals(1);
- let pocoLookupValues = dto.pocoLookup["A"];
- expect(pocoLookupValues.length).equals(2);
- expect(pocoLookupValues[0].name).equals("B");
- expect(pocoLookupValues[1].name).equals("C");
- expect(Object.keys(dto.pocoLookupMap).length).equals(1);
- let pocoLookupMapValues = dto.pocoLookupMap["A"];
- expect(Object.keys(pocoLookupMapValues).length).equals(1);
- let pocoLookupMapAList = pocoLookupMapValues[0];
- expect(Object.keys(pocoLookupMapAList).length).equals(2);
- expect(pocoLookupMapAList["B"].name).equals("C");
- expect(pocoLookupMapAList["D"].name).equals("E");
-}
-const TEST_URL = "https://test.servicestack.net";
-function createTestClient() {
- return new index_1.JsonServiceClient(TEST_URL);
-}
-describe('Serialization Tests', () => {
- it('Can POST HelloAllTypes', () => __awaiter(void 0, void 0, void 0, function* () {
- let client = createTestClient();
- let request = createHelloAllTypes();
- let response = yield client.post(request);
- assertHelloAllTypesResponse(response);
- }));
- it('Can PUT HelloAllTypes', () => __awaiter(void 0, void 0, void 0, function* () {
- let client = createTestClient();
- let request = createHelloAllTypes();
- let response = yield client.put(request);
- assertHelloAllTypesResponse(response);
- }));
-});
diff --git a/test/serverevents.spec.d.ts b/test/serverevents.spec.d.ts
deleted file mode 100644
index cb0ff5c..0000000
--- a/test/serverevents.spec.d.ts
+++ /dev/null
@@ -1 +0,0 @@
-export {};
diff --git a/test/serverevents.spec.js b/test/serverevents.spec.js
deleted file mode 100644
index b0b77ec..0000000
--- a/test/serverevents.spec.js
+++ /dev/null
@@ -1,949 +0,0 @@
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-globalThis.EventSource = require("eventsource");
-const chai = require("chai");
-const { expect, assert } = chai;
-const index_1 = require("../src/index");
-const test_dtos_1 = require("./dtos/test.dtos");
-const receivers_1 = require("./receivers");
-const run = (states, debug) => {
- let i = 0;
- const fn = () => {
- if (debug)
- debug(i);
- if (states.length == 0)
- return;
- let next = states[0];
- if (next.test()) {
- states.shift();
- // uncomment to find out the last state that was run
- // console.log("states remaining: " + states.length);
- let ret = next.fn();
- if (ret && ret.then) //Promise
- ret.then(fn)
- .catch(console.log)
- .then(fn);
- else
- fn();
- }
- };
- return fn;
-};
-const pause = () => {
- return new Promise(resolve => setTimeout(resolve, 100));
-};
-const postChat = (sse, message, channel) => {
- const request = new test_dtos_1.PostChatToChannel();
- request.from = sse.getSubscriptionId();
- request.message = message;
- request.channel = channel || index_1.ServerEventsClient.UnknownChannel;
- request.selector = "cmd.chat";
- return sse.serviceClient.post(request);
-};
-const postRaw = (sse, selector, message, channel) => {
- const request = new test_dtos_1.PostRawToChannel();
- request.from = sse.getSubscriptionId();
- request.message = message;
- request.channel = channel || index_1.ServerEventsClient.UnknownChannel;
- request.selector = selector;
- return sse.serviceClient.post(request);
-};
-const postObject = (sse, dto, selector, channel) => {
- const request = new test_dtos_1.PostObjectToChannel();
- request.customType = dto;
- request.channel = channel || index_1.ServerEventsClient.UnknownChannel;
- request.selector = selector;
- return sse.serviceClient.post(request);
-};
-const postObjectSetter = (sse, dto) => {
- const request = new test_dtos_1.PostObjectToChannel();
- request.setterType = dto;
- request.channel = index_1.ServerEventsClient.UnknownChannel;
- return sse.serviceClient.post(request);
-};
-const complete = (done, ...clients) => {
- Promise.all(clients.map(x => x.stop()))
- .then(r => done());
-};
-const SERVER_EVENTS_URL = 'https://test.servicestack.net';
-//const SERVER_EVENTS_URL = 'http://localhost:5000';
-describe('ServerEventsClient Tests', () => {
- it('Can connect to ServerEventsStream', done => {
- const client = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["*"], {
- handlers: {
- onConnect: (e => {
- // console.log('onConnect: ', e);
- complete(done, client);
- })
- }
- }).start();
- });
- it('Does fire onJoin events', done => {
- const client = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["*"], {
- handlers: {
- onConnect: ((e) => {
- expect(e.heartbeatUrl).to.satisfy(x => x.startsWith(SERVER_EVENTS_URL));
- }),
- onCommand: ((e) => {
- // console.log('onCommand: ', e);
- expect(client.getConnectionInfo().displayName).to.equal(e.displayName);
- complete(done, client);
- })
- }
- }).start();
- });
- it('Does fire onJoin events for multiple Channels', done => {
- const channels = ["A", "B", "C"];
- const joinMsgs = [];
- const client = new index_1.ServerEventsClient(SERVER_EVENTS_URL, channels, {
- handlers: {
- onJoin: ((e) => {
- // console.log(e);
- joinMsgs.push(e);
- expect(e.channel).to.equal(channels[joinMsgs.length - 1]);
- expect(client.getConnectionInfo().displayName).to.equal(e.displayName);
- if (joinMsgs.length == channels.length) {
- complete(done, client);
- }
- })
- }
- }).start();
- });
- it('Does fire all callbacks', done => {
- let connectMsgs = [];
- let msgs = [];
- let commands = [];
- let errors = [];
- let states = [];
- const client = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["*"], {
- handlers: {
- onConnect: (e => connectMsgs.push(e)),
- onCommand: (e => commands.push(e)),
- onMessage: (e => msgs.push(e)),
- onException: (e => errors.push(e))
- },
- onTick: run(states)
- }).start();
- let client2;
- states.unshift({
- test: () => connectMsgs.length == 1 && commands.filter(x => x.type == "ServerEventJoin").length == 1,
- fn() {
- const connectMsg = connectMsgs[0];
- const joinMsg = commands.filter(x => x.type == "ServerEventJoin")[0];
- expect(connectMsg).to.not.null;
- expect(joinMsg).to.not.null;
- expect(msgs.length).to.equal(0);
- expect(errors.length).to.equal(0);
- expect(commands.length).to.equal(1);
- connectMsgs = [];
- commands = [];
- client2 = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["*"], {
- handlers: {
- onConnect: (e => connectMsgs.push(e)),
- },
- onTick: run(states)
- }).start();
- }
- }, {
- test: () => connectMsgs.length == 1 && commands.length == 1,
- fn() {
- let connectMsg = connectMsgs[0];
- let joinMsg = commands.filter(x => x.type == "ServerEventJoin")[0];
- expect(connectMsg).to.not.null;
- expect(joinMsg).to.not.null;
- return client2.stop();
- }
- }, {
- test: () => commands.length == 2,
- fn() {
- let leaveMsg = commands.filter(x => x.type == "ServerEventLeave")[0];
- expect(leaveMsg).to.not.null;
- expect(errors.length).to.equal(0);
- complete(done, client);
- }
- });
- });
- it('Does receive messages', done => {
- let connectMsgs = [];
- let commands = [];
- let msgs1 = [];
- let msgs2 = [];
- let states = [];
- let client2 = null;
- const client1 = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["*"], {
- handlers: {
- onConnect: (e => connectMsgs.push(e)),
- onCommand: (e => commands.push(e)),
- onMessage: (e => msgs1.push(e))
- },
- onTick: run(states)
- }).start();
- let info1;
- let info2;
- states.unshift({
- test: () => connectMsgs.length > 0 && commands.length > 0,
- fn() {
- client2 = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["*"], {
- handlers: {
- onConnect: (e => connectMsgs.push(e)),
- onMessage: (e => msgs2.push(e))
- },
- onTick: run(states)
- }).start();
- }
- }, { test: () => connectMsgs.length > 1 && commands.length > 1,
- fn() {
- info1 = connectMsgs[0];
- return postChat(client1, "hello from client1");
- },
- }, { test: () => msgs1.length >= 1 && msgs2.length >= 1,
- fn() {
- let msg1 = msgs1[0];
- let msg2 = msgs2[0];
- expect(msg1.eventId).to.greaterThan(0);
- expect(msg2.eventId).to.greaterThan(0);
- expect(msg1.selector).to.equal("cmd.chat");
- expect(msg2.selector).to.equal("cmd.chat");
- let chatMsg1 = JSON.parse(msg1.json);
- let chatMsg2 = JSON.parse(msg2.json);
- [chatMsg1, chatMsg2].forEach(chatMsg => {
- expect(chatMsg.id).to.greaterThan(0);
- expect(chatMsg.fromUserId).to.equal(info1.userId);
- expect(chatMsg.fromName).to.equal(info1.displayName);
- });
- expect(msgs1.length).to.equal(1);
- expect(msgs2.length).to.equal(1);
- info2 = connectMsgs[1];
- return postChat(client2, "hello from client2");
- }
- }, { test: () => msgs1.length >= 2 && msgs2.length >= 2,
- fn() {
- let msg1 = msgs1[1];
- let msg2 = msgs2[1];
- let chatMsg1 = JSON.parse(msg1.json);
- let chatMsg2 = JSON.parse(msg2.json);
- [chatMsg1, chatMsg2].forEach(chatMsg => {
- expect(chatMsg.id).to.greaterThan(0);
- expect(chatMsg.fromUserId).to.equal(info2.userId);
- expect(chatMsg.fromName).to.equal(info2.displayName);
- });
- expect(msgs1.length).to.equal(2);
- expect(msgs2.length).to.equal(2);
- complete(done, client1, client2);
- }
- });
- });
- it('Does send multiple heartbeats', function (done) {
- this.timeout(10000);
- let heartbeats = [];
- const client = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["*"], {
- handlers: {
- onConnect: ((e) => e.heartbeatIntervalMs = 1000),
- onHeartbeat: (e => {
- heartbeats.push(e);
- if (heartbeats.length >= 3) {
- expect(heartbeats.length).to.greaterThan(2);
- complete(done, client);
- }
- }),
- }
- }).start();
- });
- it('Does reconnect on lost connection', function (done) {
- this.timeout(31000);
- let connectMsgs = [];
- let msgs1 = [];
- let states = [];
- let client2 = null;
- const client1 = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["*"], {
- handlers: {
- onConnect: (e => connectMsgs.push(e)),
- onMessage: (e => msgs1.push(e))
- },
- onTick: run(states)
- }).start();
- states.unshift({
- test: () => connectMsgs.length >= 1,
- fn() {
- return postChat(client1, "msg1 from client1");
- }
- }, { test: () => msgs1.length >= 1,
- fn() {
- return client1.serviceClient.post(new test_dtos_1.ResetServerEvents())
- .then(r => {
- client2 = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["*"], {
- handlers: {
- onConnect: (e => connectMsgs.push(e)),
- },
- onTick: run(states)
- }).start();
- });
- }
- }, { test: () => connectMsgs.length >= 3,
- fn() {
- return postChat(client2, "msg2 from client2");
- }
- }, { test: () => msgs1.length >= 2,
- fn() {
- let msg2 = msgs1[1];
- let chatMsg2 = JSON.parse(msg2.json);
- expect(chatMsg2.message).to.equal("msg2 from client2");
- complete(done, client1, client2);
- }
- });
- });
- it('Does send message to Handler', done => {
- let chatMsgs = [];
- let states = [];
- const client1 = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["*"], {
- handlers: {
- chat: (chatMsg, e) => {
- // console.log(chatMsg);
- chatMsgs.push(chatMsg);
- }
- },
- onTick: run(states)
- }).start();
- states.unshift({
- test: () => client1.hasConnected(),
- fn() {
- return postChat(client1, "msg1");
- }
- }, { test: () => chatMsgs.length >= 1,
- fn() {
- let chatMsg = chatMsgs[chatMsgs.length - 1];
- expect(chatMsg.message).to.equal("msg1");
- return postChat(client1, "msg2");
- }
- }, { test: () => chatMsgs.length >= 2,
- fn() {
- let chatMsg = chatMsgs[chatMsgs.length - 1];
- expect(chatMsg.message).to.equal("msg2");
- complete(done, client1);
- }
- });
- });
- it('Does send string to Handler', done => {
- let announceMsgs = [];
- let states = [];
- const client1 = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["*"], {
- handlers: {
- announce: (msg, e) => {
- // console.log(msg, e);
- announceMsgs.push(msg);
- }
- },
- onTick: run(states)
- }).start();
- states.unshift({
- test: () => client1.hasConnected(),
- fn() {
- return postRaw(client1, "cmd.announce", "msg1");
- }
- }, { test: () => announceMsgs.length >= 1,
- fn() {
- let announceMsg = announceMsgs[announceMsgs.length - 1];
- expect(announceMsg).to.equal("msg1");
- return postRaw(client1, "cmd.announce", "msg2");
- }
- }, { test: () => announceMsgs.length >= 2,
- fn() {
- let announceMsg = announceMsgs[announceMsgs.length - 1];
- expect(announceMsg).to.equal("msg2");
- complete(done, client1);
- }
- });
- });
- it('Does send message to named receiver', function (done) {
- this.timeout(10000);
- let msgs1 = [];
- let states = [];
- const client1 = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["*"], {
- handlers: {
- onMessage: e => {
- //console.log(`msg #${msgs1.length+1}:`, e);
- msgs1.push(e);
- }
- },
- receivers: {
- test: new receivers_1.TestNamedReceiver()
- },
- onTick: run(states)
- }).start();
- client1.hasConnected();
- states.unshift({
- test: () => client1.hasConnected(),
- fn() {
- const request = new test_dtos_1.CustomType();
- request.id = 1;
- request.name = "Foo";
- return postObject(client1, request, "test.fooMethod");
- }
- }, { test: () => msgs1.length >= 1,
- fn() {
- let foo = receivers_1.TestNamedReceiver.FooMethodReceived;
- expect(foo).to.not.undefined;
- expect(foo.id).to.equal(1);
- expect(foo.name).to.equal("Foo");
- const request = new test_dtos_1.CustomType();
- request.id = 2;
- request.name = "Bar";
- return postObject(client1, request, "test.barMethod");
- }
- }, { test: () => msgs1.length >= 2,
- fn() {
- let bar = receivers_1.TestNamedReceiver.BarMethodReceived;
- expect(bar).to.not.undefined;
- expect(bar.id).to.equal(2);
- expect(bar.name).to.equal("Bar");
- const request = new test_dtos_1.CustomType();
- request.id = 3;
- request.name = "Baz";
- return postObject(client1, request, "test.BazMethod");
- }
- }, { test: () => msgs1.length >= 3,
- fn() {
- let baz = receivers_1.TestNamedReceiver.NoSuchMethodReceived;
- expect(baz).to.not.undefined;
- expect(baz.id).to.equal(3);
- expect(baz.name).to.equal("Baz");
- expect(receivers_1.TestNamedReceiver.NoSuchMethodSelector).to.equal("BazMethod");
- const request = new test_dtos_1.CustomType();
- request.id = 4;
- request.name = "Qux";
- return postObject(client1, request, "test.quxSetter");
- }
- }, { test: () => msgs1.length >= 4,
- fn() {
- let qux = receivers_1.TestNamedReceiver.QuxSetterReceived;
- expect(qux).to.not.undefined;
- expect(qux.id).to.equal(4);
- expect(qux.name).to.equal("Qux");
- complete(done, client1);
- }
- });
- });
- it('Does send message to global receiver', done => {
- let msgs1 = [];
- let states = [];
- const client1 = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["*"], {
- handlers: {
- onMessage: e => msgs1.push(e)
- },
- onTick: run(states)
- })
- .registerReceiver(new receivers_1.TestGlobalReceiver())
- .start();
- states.unshift({
- test: () => client1.hasConnected(),
- fn() {
- const request = new test_dtos_1.CustomType();
- request.id = 1;
- request.name = "Foo";
- return postObject(client1, request);
- }
- }, { test: () => msgs1.length >= 1,
- fn() {
- let foo = receivers_1.TestGlobalReceiver.CustomTypeMethodReceived;
- expect(foo).to.not.undefined;
- expect(foo.id).to.equal(1);
- expect(foo.name).to.equal("Foo");
- complete(done, client1);
- }
- });
- });
- it('Does set properties on global receiver', done => {
- let msgs1 = [];
- let states = [];
- const client1 = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["*"], {
- handlers: {
- onMessage: e => msgs1.push(e)
- },
- onTick: run(states)
- })
- .registerReceiver(new receivers_1.TestGlobalReceiver())
- .start();
- states.unshift({
- test: () => client1.hasConnected(),
- fn() {
- const request = new test_dtos_1.SetterType();
- request.id = 1;
- request.name = "Foo";
- return postObjectSetter(client1, request);
- }
- }, { test: () => msgs1.length >= 1,
- fn() {
- let foo = receivers_1.TestGlobalReceiver.SetterTypeReceived;
- expect(foo).to.not.undefined;
- expect(foo.id).to.equal(1);
- expect(foo.name).to.equal("Foo");
- complete(done, client1);
- }
- });
- });
- it('Does send raw string messages', function (done) {
- this.timeout(10000);
- let msgs1 = [];
- let states = [];
- const client1 = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["*"], {
- handlers: {
- onMessage: e => msgs1.push(e)
- },
- receivers: {
- "css": new receivers_1.TestJavaScriptReceiver()
- },
- onTick: run(states)
- })
- .registerReceiver(new receivers_1.TestJavaScriptReceiver())
- .start();
- states.unshift({
- test: () => client1.hasConnected(),
- fn() {
- return postChat(client1, "chat msg");
- }
- }, { test: () => msgs1.length >= 1,
- fn() {
- let chatMsg = receivers_1.TestJavaScriptReceiver.ChatReceived;
- expect(chatMsg).to.not.undefined;
- expect(chatMsg.message).to.equal("chat msg");
- return postRaw(client1, "cmd.announce", "This is your captain speaking...");
- }
- }, { test: () => msgs1.length >= 2,
- fn() {
- let announce = receivers_1.TestJavaScriptReceiver.AnnounceReceived;
- expect(announce).to.equal("This is your captain speaking...");
- return postRaw(client1, "cmd.toggle$#channels", null);
- }
- }, { test: () => msgs1.length >= 3,
- fn() {
- let toggle = receivers_1.TestJavaScriptReceiver.ToggleReceived;
- expect(toggle).to.null;
- let toggleRequest = receivers_1.TestJavaScriptReceiver.ToggleRequestReceived;
- expect(toggleRequest.selector).to.equal("cmd.toggle$#channels");
- expect(toggleRequest.op).to.equal("cmd");
- expect(toggleRequest.target).to.equal("toggle");
- expect(toggleRequest.cssSelector).to.equal("#channels");
- return postRaw(client1, "css.background-image$#top", "url(http://bit.ly/1yIJOBH)");
- }
- }, { test: () => msgs1.length >= 4,
- fn() {
- let bgImage = receivers_1.TestJavaScriptReceiver.BackgroundImageReceived;
- expect(bgImage).to.equal("url(http://bit.ly/1yIJOBH)");
- let bgImageRequest = receivers_1.TestJavaScriptReceiver.BackgroundImageRequestReceived;
- expect(bgImageRequest.selector).to.equal("css.background-image$#top");
- expect(bgImageRequest.op).to.equal("css");
- expect(bgImageRequest.target).to.equal("background-image");
- expect(bgImageRequest.cssSelector).to.equal("#top");
- complete(done, client1);
- }
- });
- });
- it('Can reuse same instance', done => {
- let msgs1 = [];
- let states = [];
- const client1 = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["*"], {
- resolver: new index_1.SingletonInstanceResolver(),
- handlers: {
- onMessage: e => msgs1.push(e)
- },
- receivers: {
- "css": receivers_1.TestJavaScriptReceiver
- },
- onTick: run(states)
- })
- .registerReceiver(receivers_1.TestJavaScriptReceiver)
- .start();
- states.unshift({
- test: () => client1.hasConnected(),
- fn() {
- return postRaw(client1, "cmd.announce", "This is your captain speaking...");
- }
- }, { test: () => msgs1.length >= 1,
- fn() {
- let instance = client1.resolver.tryResolve(receivers_1.TestJavaScriptReceiver);
- expect(instance.AnnounceInstance).to.equal("This is your captain speaking...");
- complete(done, client1);
- }
- });
- });
- it('Does receive messages on to clients subscribed on multiple channels', done => {
- let msgsA = [];
- let msgsAB = [];
- let msgsABC = [];
- let msgsABCD = [];
- let states = [];
- const clientA = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["A"], {
- handlers: { onMessage: e => msgsA.push(e) }, onTick: run(states)
- });
- const clientAB = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["A", "B"], {
- handlers: { onMessage: e => msgsAB.push(e) }, onTick: run(states)
- });
- const clientABC = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["A", "B", "C"], {
- handlers: { onMessage: e => msgsABC.push(e) }, onTick: run(states)
- });
- const clientABCD = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["A", "B", "C", "D"], {
- handlers: { onMessage: e => msgsABCD.push(e) }, onTick: run(states)
- });
- let allClients = [clientA, clientAB, clientABC, clientABCD];
- allClients.forEach(x => x.start());
- let channelAsubscribers = [];
- let channelABsubscribers = [];
- states.unshift({
- test: () => allClients.every(x => x.hasConnected()),
- fn() {
- return Promise.all([
- clientA.getChannelSubscribers()
- .then(r => channelAsubscribers = r),
- clientAB.getChannelSubscribers()
- .then(r => channelABsubscribers = r)
- ]).then(r => {
- expect(channelAsubscribers.length).to.equal(4);
- expect(channelABsubscribers.length).to.equal(4);
- // console.log("Publishing Msg Batch #1 ...");
- return Promise.all([
- postChat(clientA, "#1 hello to A", "A"),
- postChat(clientA, "#2 hello to B", "B"),
- postChat(clientA, "#3 hello to C", "C"),
- postChat(clientA, "#4 hello to D", "D")
- ]);
- });
- }
- }, { test: () => (msgsA.length + msgsAB.length + msgsABC.length + msgsABCD.length) == 10,
- fn() {
- expect(msgsA.length).to.equal(1);
- expect(msgsAB.length).to.equal(2);
- expect(msgsABC.length).to.equal(3);
- expect(msgsABCD.length).to.equal(4);
- // console.log("Publishing Msg Batch #2 ...");
- return Promise.all([
- postChat(clientA, "#5 hello to A", "A"),
- postChat(clientA, "#6 hello to B", "B"),
- postChat(clientA, "#7 hello to C", "C"),
- postChat(clientA, "#8 hello to D", "D")
- ]);
- }
- }, { test: () => (msgsA.length + msgsAB.length + msgsABC.length + msgsABCD.length) == 20,
- fn() {
- expect(msgsA.length).to.equal(2);
- expect(msgsAB.length).to.equal(4);
- expect(msgsABC.length).to.equal(6);
- expect(msgsABCD.length).to.equal(8);
- complete(done, ...allClients);
- }
- });
- });
- it('Does receive all join and leave messages', function (done) {
- this.timeout(10000);
- let joinA = [];
- let joinB = [];
- let joinAB = [];
- let leaveA = [];
- let leaveB = [];
- let leaveAB = [];
- let states = [];
- const clientA = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["A"], {
- handlers: { onJoin: e => joinA.push(e), onLeave: e => leaveA.push(e) }, onTick: run(states)
- });
- const clientB = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["B"], {
- handlers: { onJoin: e => joinB.push(e), onLeave: e => leaveB.push(e) }, onTick: run(states)
- });
- const clientAB = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["A", "B"], {
- handlers: { onJoin: e => joinAB.push(e), onLeave: e => leaveAB.push(e) }, onTick: run(states)
- });
- let allClients = [clientA, clientB, clientAB];
- [clientA, clientB].forEach(x => x.start());
- states.unshift({
- test: () => clientA.hasConnected() && clientB.hasConnected(),
- fn() {
- return clientAB.start();
- }
- }, { test: () => joinA.length >= 2 && joinB.length >= 2 && joinAB.length >= 2,
- fn() {
- expect(joinA.length).to.equal(2); //A + [(A) B]
- expect(joinB.length).to.equal(2); //B + [A (B)]
- expect(joinAB.length).to.equal(2); //[(A) B] + [A (B)]
- return Promise.all([
- clientA.getChannelSubscribers().then(r => expect(r.length).to.equal(2)),
- clientB.getChannelSubscribers().then(r => expect(r.length).to.equal(2)),
- clientAB.getChannelSubscribers().then(r => expect(r.length).to.equal(3))
- ])
- .then(r => {
- const createRequest = (...channels) => {
- let request = new index_1.GetEventSubscribers();
- request.channels = channels;
- return request;
- };
- return Promise.all([
- clientA.serviceClient.get(createRequest("A")).then(r => expect(r.length).to.equal(2)),
- clientB.serviceClient.get(createRequest("B")).then(r => expect(r.length).to.equal(2)),
- clientAB.serviceClient.get(createRequest("A", "B")).then(r => expect(r.length).to.equal(3))
- ]);
- })
- .then(r => clientAB.stop());
- }
- }, { test: () => leaveA.length + leaveB.length >= 2,
- fn() {
- return Promise.all([clientA.stop(), clientB.stop()])
- .then(r => {
- expect(leaveA.length).to.equal(1);
- expect(leaveB.length).to.equal(1);
- expect(leaveAB.length).to.equal(0);
- complete(done);
- });
- }
- });
- });
- it('MultiChannel Does receive all join and leave messages', function (done) {
- this.timeout(10000);
- let joinA = [];
- let joinB = [];
- let joinAB = [];
- let leaveA = [];
- let leaveB = [];
- let leaveAB = [];
- let states = [];
- const clientA = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["A"], {
- handlers: { onJoin: e => joinA.push(e), onLeave: e => leaveA.push(e) }, onTick: run(states)
- });
- const clientB = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["B"], {
- handlers: { onJoin: e => joinB.push(e), onLeave: e => leaveB.push(e) }, onTick: run(states)
- });
- const clientAB = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["A", "B"], {
- handlers: { onJoin: e => joinAB.push(e), onLeave: e => leaveAB.push(e) }, onTick: run(states)
- });
- let allClients = [clientA, clientB, clientAB];
- clientAB.start();
- states.unshift({
- test: () => clientAB.hasConnected(),
- fn() {
- return Promise.all([clientA.start(), clientB.start()]);
- }
- }, { test: () => joinAB.length >= 4 && joinA.length >= 1 && joinB.length >= 1,
- fn() {
- expect(joinAB.length).to.equal(4); //[(A) B] + [A (B)] + A + B
- expect(joinA.length).to.equal(1);
- expect(joinB.length).to.equal(1);
- return Promise.all([clientA.stop(), clientB.stop()])
- .then(pause);
- }
- }, { test: () => leaveAB.length >= 2,
- fn() {
- expect(leaveAB.length).to.equal(2);
- expect(leaveA.length).to.equal(0);
- expect(leaveB.length).to.equal(0);
- complete(done, clientAB);
- }
- });
- });
- it('Can subscribe to channels whilst connected', function (done) {
- this.timeout(10000);
- let msgs1 = [];
- let msgs2 = [];
- let states = [];
- const client1 = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["A"], {
- handlers: { onMessage: e => msgs1.push(e) },
- onTick: run(states)
- }).start();
- const client2 = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["B"], {
- handlers: { onMessage: e => msgs2.push(e) },
- onTick: run(states)
- }).start();
- states.unshift({
- test: () => client1.hasConnected() && client2.hasConnected(),
- fn() {
- expect(client1.channels).to.deep.equal(["A"]);
- return postChat(client2, "#1 hello to B", "B");
- }
- }, { test: () => msgs1.length + msgs2.length >= 1,
- fn() {
- expect(msgs1.length).to.equal(0);
- expect(msgs2.length).to.equal(1);
- return client1.subscribeToChannels("B");
- }
- }, { test: () => client1.channels.indexOf("B") >= 0,
- fn() {
- expect(client1.channels).to.deep.equal(["A", "B"]);
- expect(client2.channels).to.deep.equal(["B"]);
- expect(client1.eventStreamUri.split('&')[0]).to.satisfy(x => x.endsWith("?channels=A,B"));
- expect(client2.eventStreamUri.split('&')[0]).to.satisfy(x => x.endsWith("?channels=B"));
- return Promise.all([
- postChat(client2, "#2 hello to B", "B"),
- postChat(client2, "#3 hello to C", "C")
- ]);
- }
- }, { test: () => msgs1.length + msgs2.length >= 3,
- fn() {
- expect(msgs1.length).to.equal(1);
- expect(msgs2.length).to.equal(2);
- return Promise.all([
- client1.subscribeToChannels("C"),
- client2.subscribeToChannels("C")
- ]);
- }
- }, { test: () => client1.channels.indexOf("C") >= 0 && client2.channels.indexOf("C") >= 0,
- fn() {
- return postChat(client2, "#4 hello to C", "C");
- }
- }, { test: () => msgs1.length + msgs2.length >= 5,
- fn() {
- expect(client1.channels).to.deep.equal(["A", "B", "C"]);
- expect(client2.channels).to.deep.equal(["B", "C"]);
- expect(client1.eventStreamUri.split('&')[0]).to.satisfy(x => x.endsWith("?channels=A,B,C"));
- expect(client2.eventStreamUri.split('&')[0]).to.satisfy(x => x.endsWith("?channels=B,C"));
- expect(msgs1.length).to.equal(2);
- expect(msgs2.length).to.equal(3);
- complete(done, client1, client2);
- }
- });
- });
- it('Can unsubscribe from channels whilst connected', function (done) {
- this.timeout(15000);
- let msgs1 = [];
- let msgs2 = [];
- let states = [];
- const client1 = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["A", "B", "C"], {
- handlers: { onMessage: e => msgs1.push(e) },
- onTick: run(states)
- }).start();
- const client2 = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["B", "C"], {
- handlers: { onMessage: e => msgs2.push(e) },
- onTick: run(states)
- }).start();
- states.unshift({
- test: () => client1.hasConnected() && client2.hasConnected(),
- fn() {
- expect(client1.channels).to.deep.equal(["A", "B", "C"]);
- return postChat(client2, "#1 hello to B", "B");
- }
- }, { test: () => msgs1.length + msgs2.length >= 2,
- fn() {
- expect(msgs1.length).to.equal(1);
- expect(msgs2.length).to.equal(1);
- return client1.unsubscribeFromChannels("B");
- }
- }, { test: () => client1.channels.indexOf("B") == -1,
- fn() {
- return Promise.all([
- postChat(client2, "#2 hello to B", "B"),
- postChat(client2, "#3 hello to C", "C")
- ]);
- }
- }, { test: () => msgs1.length + msgs2.length >= 5,
- fn() {
- expect(msgs1.length).to.equal(2);
- expect(msgs2.length).to.equal(3);
- expect(client1.channels).to.deep.equal(["A", "C"]);
- expect(client2.channels).to.deep.equal(["B", "C"]);
- expect(client1.eventStreamUri.split('&')[0]).to.satisfy(x => x.endsWith("?channels=A,C"));
- expect(client2.eventStreamUri.split('&')[0]).to.satisfy(x => x.endsWith("?channels=B,C"));
- return Promise.all([
- client1.unsubscribeFromChannels("C"),
- client2.unsubscribeFromChannels("C")
- ]).then(r => postChat(client2, "#4 hello to C", "C"));
- }
- }, { test: () => client1.channels.indexOf("C") == -1 && client2.channels.indexOf("C") == -1,
- fn() {
- expect(client1.channels).to.deep.equal(["A"]);
- expect(client2.channels).to.deep.equal(["B"]);
- expect(client1.eventStreamUri.split('&')[0]).to.satisfy(x => x.endsWith("?channels=A"));
- expect(client2.eventStreamUri.split('&')[0]).to.satisfy(x => x.endsWith("?channels=B"));
- complete(done, client1, client2);
- }
- });
- });
- it('Does fire multiple listeners for custom trigger', done => {
- let msgs1 = [];
- let msgs2 = [];
- const handler = (e) => {
- msgs1.push(e);
- };
- let states = [];
- const client1 = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["*"], {
- onTick: run(states)
- })
- .addListener("customEvent", handler)
- .addListener("customEvent", e => msgs2.push(e))
- .start();
- const client2 = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["*"], {
- onTick: run(states)
- }).start();
- states.unshift({
- test: () => client1.hasConnected() && client2.hasConnected(),
- fn() {
- postRaw(client2, "trigger.customEvent", "arg");
- }
- }, { test: () => msgs1.length >= 1 && msgs2.length >= 1,
- fn() {
- expect(msgs1.length).to.equal(1);
- expect(msgs2.length).to.equal(1);
- client1.removeListener("customEvent", handler);
- postRaw(client2, "trigger.customEvent", "arg");
- }
- }, { test: () => msgs2.length >= 2,
- fn() {
- expect(msgs1.length).to.equal(1);
- expect(msgs2.length).to.equal(2);
- expect([...msgs1, ...msgs2].every(x => JSON.parse(x.json) == "arg")).to.be.true;
- complete(done, client1, client2);
- }
- });
- });
- it("Does raise Error Messages", done => {
- let errors = [];
- let states = [];
- const client1 = new index_1.ServerEventsClient('http://chat.servicestack.invalid', ["*"], {
- onException: (e) => {
- expect(e).to.exist;
- errors.push(e);
- },
- onTick: run(states)
- }).start();
- const client2 = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["*"], {
- onTick: run(states)
- }).start();
- let client3;
- states.unshift({
- test: () => errors.length >= 1,
- fn() {
- client3 = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["*"], {
- handlers: {
- onConnect: (e) => {
- e.heartbeatIntervalMs = 1000;
- },
- },
- onException: function (e) {
- expect(e).to.exist;
- errors.push(e);
- },
- onTick: run(states)
- }).start();
- }
- }, { test: () => client3.hasConnected() && client2.hasConnected(),
- fn() {
- return client2.serviceClient.post(new test_dtos_1.ResetServerEvents());
- }
- }, { test: () => errors.length >= 2,
- fn() {
- // errors.forEach(e => console.log(e.message));
- complete(done, client1, client2, client3);
- }
- });
- });
- it('Does create EventSource instance withCredentials', () => {
- let client = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["*"], {})
- .start();
- expect(client.getEventSourceOptions().withCredentials).eq(true);
- if (typeof window != "undefined") {
- expect(client.eventSource.withCredentials).eq(true);
- }
- client.stop();
- client = new index_1.ServerEventsClient(SERVER_EVENTS_URL, ["*"], {});
- client.withCredentials = false;
- client.start();
- expect(client.getEventSourceOptions().withCredentials).eq(false);
- if (typeof window != "undefined") {
- expect(client.eventSource.withCredentials).eq(false);
- }
- client.stop();
- });
-});
diff --git a/test/stringbuffer.spec.d.ts b/test/stringbuffer.spec.d.ts
deleted file mode 100644
index cb0ff5c..0000000
--- a/test/stringbuffer.spec.d.ts
+++ /dev/null
@@ -1 +0,0 @@
-export {};
diff --git a/test/stringbuffer.spec.js b/test/stringbuffer.spec.js
deleted file mode 100644
index 2069f82..0000000
--- a/test/stringbuffer.spec.js
+++ /dev/null
@@ -1,63 +0,0 @@
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-const chai = require("chai");
-const { expect, assert } = chai;
-const index_1 = require("../src/index");
-describe('StringBuffer Tests', () => {
- it('StringBuffer', () => {
- let sb = new index_1.StringBuffer();
- sb.append('Four score');
- sb.append(' ');
- sb.append('and seven years ago.');
- expect(sb.toString()).eq('Four score and seven years ago.');
- sb.clear();
- expect(sb.toString()).eq('');
- sb = new index_1.StringBuffer('Four score ');
- sb.append('and seven years ago.');
- expect(sb.toString()).eq('Four score and seven years ago.');
- // can pass in non-Strings?
- sb = new index_1.StringBuffer(1);
- sb.append(2);
- expect(sb.toString()).eq('12');
- });
- it('StringBuffer Set', () => {
- const sb = new index_1.StringBuffer('foo');
- sb.set('bar');
- expect(sb.toString()).eq('bar');
- });
- it('StringBuffer Multi Append', () => {
- let sb = new index_1.StringBuffer('hey', 'foo');
- sb.append('bar', 'baz');
- expect(sb.toString()).eq('heyfoobarbaz');
- sb = new index_1.StringBuffer();
- sb.append(1, 2);
- // should not add up to '3'
- expect(sb.toString()).eq('12');
- });
- it('StringBuffer toString', () => {
- const sb = new index_1.StringBuffer('foo', 'bar');
- expect(sb.toString()).eq('foobar');
- });
- it('StringBuffer with false First Argument', () => {
- let sb = new index_1.StringBuffer(0, 'more');
- expect(sb.toString()).eq('0more');
- sb = new index_1.StringBuffer(false, 'more');
- expect(sb.toString()).eq('falsemore');
- sb = new index_1.StringBuffer('', 'more');
- expect(sb.toString()).eq('more');
- sb = new index_1.StringBuffer(null, 'more');
- expect(sb.toString()).eq('');
- sb = new index_1.StringBuffer(undefined, 'more');
- expect(sb.toString()).eq('');
- });
- it('StringBuffer getLength', () => {
- const sb = new index_1.StringBuffer();
- expect(sb.getLength()).eq(0);
- sb.append('foo');
- expect(sb.getLength()).eq(3);
- sb.append('baroo');
- expect(sb.getLength()).eq(8);
- sb.clear();
- expect(sb.getLength()).eq(0);
- });
-});
diff --git a/test/usages.spec.d.ts b/test/usages.spec.d.ts
deleted file mode 100644
index cb0ff5c..0000000
--- a/test/usages.spec.d.ts
+++ /dev/null
@@ -1 +0,0 @@
-export {};
diff --git a/test/usages.spec.js b/test/usages.spec.js
deleted file mode 100644
index 7b8513b..0000000
--- a/test/usages.spec.js
+++ /dev/null
@@ -1,31 +0,0 @@
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-const chai = require("chai");
-const { expect, assert } = chai;
-const index_1 = require("../src/index");
-describe('Usages Tests', () => {
- it('Can configure basePath and headers', () => {
- const client = new index_1.JsonServiceClient('https://example.org')
- .apply(c => {
- c.basePath = '/api';
- c.headers = new Headers();
- });
- expect(client.replyBaseUrl).eq('https://example.org/api/');
- expect(client.oneWayBaseUrl).eq('https://example.org/api/');
- expect(Array.from(client.headers.keys()).length).eq(0);
- });
- it('Does map each item and returns result', () => {
- let o = { a: 1, b: 2 };
- let r = (0, index_1.each)(Object.keys(o), (acc, k) => acc[k] = o[k] * 2);
- expect(r.a).eq(2);
- expect(r.b).eq(4);
- r = (0, index_1.each)(Object.keys(o), (acc, k) => acc[k] = o[k] * 2, { c: 1 });
- expect(r.a).eq(2);
- expect(r.b).eq(4);
- expect(r.c).eq(1);
- });
- it('Does allow usage of FormData from node', () => {
- const formData = new FormData();
- formData.append('a', 'b');
- });
-});
diff --git a/test/utils.spec.d.ts b/test/utils.spec.d.ts
deleted file mode 100644
index cb0ff5c..0000000
--- a/test/utils.spec.d.ts
+++ /dev/null
@@ -1 +0,0 @@
-export {};
diff --git a/test/utils.spec.js b/test/utils.spec.js
deleted file mode 100644
index b346f8b..0000000
--- a/test/utils.spec.js
+++ /dev/null
@@ -1,102 +0,0 @@
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-const chai = require("chai");
-const { expect, assert } = chai;
-const index_1 = require("../src/index");
-const dist_1 = require("../dist");
-const test_dtos_1 = require("./dtos/test.dtos");
-describe('Util Tests', () => {
- it('Can parse cookie', done => {
- var cookie = (0, index_1.parseCookie)('ss-pid=2quSav3JNK2T3Xbf7MiU; expires=Thu, 12-Mar-2037 12:54:06 GMT; path=/; HttpOnly');
- expect(cookie.name).eq("ss-pid");
- expect(cookie.value).eq("2quSav3JNK2T3Xbf7MiU");
- expect(cookie.path).eq("/");
- expect(cookie.expires.getFullYear()).eq(2037);
- expect(cookie.expires.getMonth() + 1).eq(3);
- expect(cookie.expires.getDate()).eq(12);
- expect(cookie.httpOnly).eq(true);
- done();
- });
- it('errorMessage returns error summary when no field specified', () => {
- const errorCode = "ERROR_CODE";
- const message = "The Message";
- expect(index_1.errorResponse.call({ responseStatus: { message, errorCode } })).eq(message);
- expect(index_1.errorResponse.call({ responseStatus: { errorCode } })).eq(errorCode);
- expect(index_1.errorResponse.call({ ResponseStatus: { message, errorCode } })).eq(message);
- expect(index_1.errorResponse.call({ ResponseStatus: { errorCode } })).eq(errorCode);
- expect(index_1.errorResponse.call({ ResponseStatus: { Message: message, ErrorCode: errorCode } })).eq(message);
- expect(index_1.errorResponse.call({ ResponseStatus: { ErrorCode: errorCode } })).eq(errorCode);
- });
- it('errorMessage returns undefined when field specified', () => {
- const errorCode = "ERROR_CODE";
- const message = "The Message";
- const fieldName = "TheField";
- expect(index_1.errorResponse.call({ responseStatus: { message, errorCode } }, fieldName)).undefined;
- expect(index_1.errorResponse.call({ responseStatus: { errorCode } }, fieldName)).undefined;
- expect(index_1.errorResponse.call({ ResponseStatus: { message, errorCode } }, fieldName)).undefined;
- expect(index_1.errorResponse.call({ ResponseStatus: { errorCode } }, fieldName)).undefined;
- expect(index_1.errorResponse.call({ ResponseStatus: { Message: message, ErrorCode: errorCode } }, fieldName)).undefined;
- expect(index_1.errorResponse.call({ ResponseStatus: { ErrorCode: errorCode } }, fieldName)).undefined;
- });
- it('errorMessage returns field error when field specified', () => {
- const errorCode = "ERROR_CODE";
- const message = "The Message";
- const fieldName = "TheField";
- const fieldMessage = "Field Message";
- const errors = [{ errorCode: "FIELD_ERROR", message: fieldMessage, fieldName }];
- expect(index_1.errorResponse.call({ responseStatus: { message, errorCode, errors } }, fieldName)).eq(fieldMessage);
- expect(index_1.errorResponse.call({ responseStatus: { errorCode, errors } }, fieldName)).eq(fieldMessage);
- expect(index_1.errorResponse.call({ ResponseStatus: { message, errorCode, errors } }, fieldName)).eq(fieldMessage);
- expect(index_1.errorResponse.call({ ResponseStatus: { errorCode, errors } }, fieldName)).eq(fieldMessage);
- expect(index_1.errorResponse.call({ ResponseStatus: { Message: message, ErrorCode: errorCode, Errors: errors } }, fieldName)).eq(fieldMessage);
- expect(index_1.errorResponse.call({ ResponseStatus: { ErrorCode: errorCode, Errors: errors } }, fieldName)).eq(fieldMessage);
- });
- it('errorResponseExcept returns undefined when Except fieldName exists', () => {
- const errorCode = "ERROR_CODE";
- const message = "The Message";
- const fieldName = "TheField";
- const fieldMessage = "Field Message";
- const errors = [{ errorCode: "FIELD_ERROR", message: fieldMessage, fieldName }];
- expect(index_1.errorResponseExcept.call({ responseStatus: { message, errorCode, errors } }, fieldName)).undefined;
- expect(index_1.errorResponseExcept.call({ responseStatus: { message, errorCode, errors } }, fieldName.toUpperCase())).undefined;
- expect(index_1.errorResponseExcept.call({ responseStatus: { message, errorCode, errors } }, [fieldName])).undefined;
- expect(index_1.errorResponseExcept.call({ responseStatus: { message, errorCode, errors } }, [fieldName.toUpperCase()])).undefined;
- expect(index_1.errorResponseExcept.call({ responseStatus: { message, errorCode, errors } }, ['AnotherFieldName', fieldName.toUpperCase()])).undefined;
- expect(index_1.errorResponseExcept.call({ responseStatus: { message, errorCode, errors } }, `AnotherFieldName,${fieldName.toUpperCase()}`)).undefined;
- });
- it('errorResponseExcept returns first unspecified error or message summary if no field match found', () => {
- const errorCode = "ERROR_CODE";
- const message = "The Message";
- const fieldName = "TheField";
- const fieldMessage = "Field Message";
- const errors = [{ errorCode: "FIELD_ERROR", message: fieldMessage, fieldName }];
- expect(index_1.errorResponseExcept.call({ responseStatus: { message, errorCode, errors } }, ['AnotherFieldName'])).eq(fieldMessage);
- expect(index_1.errorResponseExcept.call({ responseStatus: { message, errorCode } }, ['AnotherFieldName'])).eq(message);
- expect(index_1.errorResponseExcept.call({ responseStatus: { errorCode } }, ['AnotherFieldName'])).eq(errorCode);
- expect(index_1.errorResponseExcept.call({ responseStatus: { message, errorCode } }, [fieldName])).eq(message);
- expect(index_1.errorResponseExcept.call({ responseStatus: { errorCode } }, [fieldName])).eq(errorCode);
- });
- it('returns object with specified field names', () => {
- const o = { a: 1, foo: "bar", active: true };
- expect(index_1.toObject.call(o, ['a'])).deep.eq({ a: 1 });
- expect(index_1.toObject.call(o, 'a foo unknown'.split(' '))).deep.eq({ a: 1, foo: "bar" });
- expect(index_1.toObject.call(o, Object.keys(o))).deep.eq(o);
- });
- it('Can base64 encode', () => {
- expect(index_1.JsonServiceClient.toBase64("Aa1&/:+=!()|[]@")).eq("QWExJi86Kz0hKCl8W11A");
- });
- it('Does humanify', () => {
- expect((0, dist_1.humanify)('a')).eq('A');
- expect((0, dist_1.humanify)('aBc')).eq('A Bc');
- expect((0, dist_1.humanify)('TheId')).eq('The Id');
- expect((0, dist_1.humanify)('TheID')).eq('The ID');
- expect((0, dist_1.humanify)('TheIDWithWord')).eq('The ID With Word');
- expect((0, dist_1.humanify)('TheID2WithWord')).eq('The ID2 With Word');
- expect((0, dist_1.humanify)('Leave me Alone!')).eq('Leave me Alone!');
- });
- it('Resolves correct HTTP Method', () => {
- expect((0, index_1.getMethod)(new test_dtos_1.Hello())).eq('POST');
- expect((0, index_1.getMethod)(new test_dtos_1.Hello(), 'GET')).eq('GET');
- expect((0, index_1.getMethod)(new test_dtos_1.Hello(), 'PUT')).eq('PUT');
- });
-});