Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: enable lint on tests for api, interactions, predictions, pubsub packages #13547

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ describe('ConnectionStateMonitor', () => {
let reachabilityObserver: Observer<{ online: boolean }>;

beforeEach(() => {
const spyon = jest
jest
.spyOn(Reachability.prototype, 'networkMonitor')
.mockImplementationOnce(() => {
return new Observable(observer => {
Expand Down
78 changes: 38 additions & 40 deletions packages/pubsub/__tests__/PubSub.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,13 @@ jest.mock('@aws-amplify/core', () => ({
},
}));

const pahoClientMockCache = {};
const pahoClientMockCache: Record<string, object> = {};

const mockConnect = jest.fn(options => {
options.onSuccess();
});

const pahoClientMock = jest.fn().mockImplementation((host, clientId) => {
const pahoClientMock = jest.fn().mockImplementation((_host, clientId) => {
if (pahoClientMockCache[clientId]) {
return pahoClientMockCache[clientId];
}
Expand All @@ -47,12 +47,12 @@ const pahoClientMock = jest.fn().mockImplementation((host, clientId) => {
client.send = jest.fn((topic, message) => {
client.onMessageArrived({ destinationName: topic, payloadString: message });
});
client.subscribe = jest.fn((topics, options) => {});
client.unsubscribe = jest.fn(() => {});
client.onMessageArrived = jest.fn(() => {});
client.subscribe = jest.fn();
client.unsubscribe = jest.fn();
client.onMessageArrived = jest.fn();

client.isConnected = jest.fn(() => true);
client.disconnect = jest.fn(() => {});
client.disconnect = jest.fn();

pahoClientMockCache[clientId] = client;

Expand All @@ -65,8 +65,7 @@ jest.mock('../src/vendor/paho-mqtt', () => ({
Client: {},
}));

// @ts-ignore
Paho.Client = pahoClientMock;
(Paho as any).Client = pahoClientMock;

const testPubSubAsync = (
pubsub,
Expand All @@ -75,10 +74,11 @@ const testPubSubAsync = (
options?,
hubConnectionListener?,
) =>
// eslint-disable-next-line no-async-promise-executor
new Promise(async (resolve, reject) => {
if (hubConnectionListener === undefined) {
hubConnectionListener = new HubConnectionListener('pubsub');
}
const resolvedHubConnectionListener =
hubConnectionListener ?? new HubConnectionListener('pubsub');

const obs = pubsub.subscribe({ topics: topic, options }).subscribe({
next: data => {
expect(data).toEqual(message);
Expand All @@ -90,7 +90,7 @@ const testPubSubAsync = (
},
error: reject,
});
await hubConnectionListener.waitUntilConnectionStateIn([
await resolvedHubConnectionListener.waitUntilConnectionStateIn([
ConnectionState.Connected,
]);
pubsub.publish({ topics: topic, message, options });
Expand All @@ -115,7 +115,9 @@ describe('PubSub', () => {

describe('constructor test', () => {
test('happy case', () => {
const pubsub = new IotPubSub();
expect(() => {
const _ = new IotPubSub();
}).not.toThrow();
});
});

Expand Down Expand Up @@ -301,19 +303,17 @@ describe('PubSub', () => {
hubConnectionListener = new HubConnectionListener('pubsub');

// Setup a mock of the reachability monitor where the initial value is online.
const spyon = jest
jest
.spyOn(Reachability.prototype, 'networkMonitor')
.mockImplementationOnce(
() =>
// @ts-ignore
new Observable(observer => {
reachabilityObserver = observer;
}),
)
// Twice because we subscribe to get the initial state then again to monitor reachability
.mockImplementationOnce(
() =>
// @ts-ignore
new Observable(observer => {
reachabilityObserver = observer;
}),
Expand All @@ -330,7 +330,7 @@ describe('PubSub', () => {
const sub = pubsub
.subscribe({ topics: 'topic', options: { clientId: '123' } })
.subscribe({
error: () => {},
error: jest.fn(),
});

await hubConnectionListener.waitUntilConnectionStateIn([
Expand All @@ -356,10 +356,10 @@ describe('PubSub', () => {
endpoint: 'wss://iot.mymockendpoint.org:443/notrealmqtt',
});

const sub = pubsub
pubsub
.subscribe({ topics: 'topic', options: { clientId: '123' } })
.subscribe({
error: () => {},
error: jest.fn(),
});

await hubConnectionListener.waitUntilConnectionStateIn([
Expand Down Expand Up @@ -391,10 +391,10 @@ describe('PubSub', () => {
endpoint: 'wss://iot.mymockendpoint.org:443/notrealmqtt',
});

const sub = pubsub
pubsub
.subscribe({ topics: 'topic', options: { clientId: '123' } })
.subscribe({
error: () => {},
error: jest.fn(),
});

await hubConnectionListener.waitUntilConnectionStateIn([
Expand Down Expand Up @@ -434,7 +434,7 @@ describe('PubSub', () => {
provider: 'MqttOverWSProvider',
});

expect(pubsub.isSSLEnabled).toBe(false);
expect((pubsub as any).isSSLEnabled).toBe(false);
expect(mockConnect).toHaveBeenCalledWith({
useSSL: false,
mqttVersion: 3,
Expand Down Expand Up @@ -484,21 +484,21 @@ describe('PubSub', () => {
endpoint: 'wss://iot.mymockendpoint.org:443/notrealmqtt',
});

const mqttClient = new MqttPubSubTest({
const _ = new MqttPubSubTest({
region: 'region',
endpoint: 'wss://iot.mymockendpoint.org:443/notrealmqtt',
});

jest.spyOn(iotClient, 'publish').mockImplementationOnce(() => {
return Promise.reject('Failed to publish');
return Promise.reject(new Error('Failed to publish'));
});

expect(
iotClient.publish({
topics: 'topicA',
message: { msg: 'my message AWSIoTProvider' },
}),
).rejects.toMatch('Failed to publish');
).rejects.toThrow('Failed to publish');
});

test('On unsubscribe when is the last observer it should disconnect the websocket', async () => {
Expand Down Expand Up @@ -548,19 +548,17 @@ describe('PubSub', () => {

const spyDisconnect = jest.spyOn(pubsub, 'disconnect');

const subscription1 = pubsub
.subscribe({ topics: ['topic1', 'topic2'] })
.subscribe({
next: _data => {
console.log({ _data });
},
complete: () => {
console.log('done');
},
error: error => {
console.log('error', error);
},
});
pubsub.subscribe({ topics: ['topic1', 'topic2'] }).subscribe({
next: _data => {
console.log({ _data });
},
complete: () => {
console.log('done');
},
error: error => {
console.log('error', error);
},
});

const subscription2 = pubsub
.subscribe({ topics: ['topic3', 'topic4'] })
Expand All @@ -578,8 +576,8 @@ describe('PubSub', () => {

// TODO: we should now when the connection is established to wait for that first
await (() => {
return new Promise(res => {
setTimeout(res, 100);
return new Promise((resolve, _reject) => {
setTimeout(resolve, 100);
});
})();

Expand Down
52 changes: 24 additions & 28 deletions packages/pubsub/__tests__/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export class HubConnectionListener {
}

/**
* @returns {Observable<ConnectionState>} - The observable that emits all ConnectionState updates (past and future)
* @returns `Observable<ConnectionState>` - The observable that emits all ConnectionState updates (past and future)
*/
allConnectionStateObserver() {
return new Observable(observer => {
Expand All @@ -46,7 +46,7 @@ export class HubConnectionListener {
}

/**
* @returns {Observable<ConnectionState>} - The observable that emits ConnectionState updates (past and future)
* @returns `Observable<ConnectionState>` - The observable that emits ConnectionState updates (past and future)
*/
connectionStateObserver() {
return new Observable(observer => {
Expand All @@ -65,21 +65,21 @@ export class HubConnectionListener {
}

async waitForConnectionState(connectionStates: CS[]) {
return new Promise<void>((res, rej) => {
return new Promise<void>((resolve, _reject) => {
this.connectionStateObserver().subscribe(value => {
if (connectionStates.includes(String(value) as CS)) {
res(undefined);
resolve(undefined);
}
});
});
}

async waitUntilConnectionStateIn(connectionStates: CS[]) {
return new Promise<void>((res, rej) => {
return new Promise<void>((resolve, _reject) => {
if (connectionStates.includes(this.currentConnectionState)) {
res(undefined);
resolve(undefined);
}
res(this.waitForConnectionState(connectionStates));
resolve(this.waitForConnectionState(connectionStates));
});
}
}
Expand All @@ -98,12 +98,12 @@ export class FakeWebSocketInterface {
}

resetWebsocket() {
this.readyForUse = new Promise((res, rej) => {
this.readyResolve = res;
this.readyForUse = new Promise((resolve, _reject) => {
this.readyResolve = resolve;
});
let closeResolver: (value: PromiseLike<any>) => void;
this.hasClosed = new Promise((res, rej) => {
closeResolver = res;
this.hasClosed = new Promise((resolve, _reject) => {
closeResolver = resolve;
});
this.webSocket = new FakeWebSocket(() => closeResolver);
}
Expand Down Expand Up @@ -233,7 +233,7 @@ export class FakeWebSocketInterface {
/**
* Send a data message
*/
async sendDataMessage(data: {}) {
async sendDataMessage(data: object) {
Copy link
Member

@AllanZhengYP AllanZhengYP Jun 27, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this right? Can data be a string?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Noticeably this function is not even used by the tests.

await this.sendMessage(
new MessageEvent('data', {
data: JSON.stringify({
Expand All @@ -257,7 +257,7 @@ export class FakeWebSocketInterface {
/**
* Run a command and resolve to allow internal behavior to execute
*/
async runAndResolve(fn) {
async runAndResolve(fn: () => Promise<unknown> | void) {
await fn();
await Promise.resolve();
}
Expand All @@ -266,10 +266,10 @@ export class FakeWebSocketInterface {
* DELETE THIS?
*/
async observesConnectionState(connectionState: CS) {
return new Promise<void>((res, rej) => {
return new Promise<void>((resolve, _reject) => {
this.allConnectionStateObserver().subscribe(value => {
if (value === connectionState) {
res(undefined);
resolve(undefined);
}
});
});
Expand Down Expand Up @@ -306,7 +306,7 @@ class FakeWebSocket implements WebSocket {
protocol!: string;
readyState!: number;
url!: string;
close(code?: number, reason?: string): void {
close(): void {
const closeResolver = this.closeResolverFcn();
if (closeResolver) closeResolver(Promise.resolve(undefined));
}
Expand All @@ -316,10 +316,10 @@ class FakeWebSocket implements WebSocket {
this.subscriptionId = parsedInput.id;
}

CONNECTING: 0 = 0;
OPEN: 1 = 1;
CLOSING: 2 = 2;
CLOSED: 3 = 3;
CONNECTING: 0 = 0 as const;
OPEN: 1 = 1 as const;
CLOSING: 2 = 2 as const;
CLOSED: 3 = 3 as const;
addEventListener<K extends keyof WebSocketEventMap>(
type: K,
listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any,
Expand All @@ -332,7 +332,7 @@ class FakeWebSocket implements WebSocket {
options?: boolean | AddEventListenerOptions,
): void;

addEventListener(type: unknown, listener: unknown, options?: unknown): void {
addEventListener(): void {
throw new Error('Method not implemented addEventListener.');
}

Expand All @@ -348,15 +348,11 @@ class FakeWebSocket implements WebSocket {
options?: boolean | EventListenerOptions,
): void;

removeEventListener(
type: unknown,
listener: unknown,
options?: unknown,
): void {
removeEventListener(): void {
throw new Error('Method not implemented removeEventListener.');
}

dispatchEvent(event: Event): boolean {
dispatchEvent(): boolean {
throw new Error('Method not implemented dispatchEvent.');
}

Expand All @@ -370,7 +366,7 @@ export async function replaceConstant(
replacementValue: any,
testFn: () => Promise<void>,
) {
const initialValue = constants[name];
const initialValue = (constants as any)[name];
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why cast as any than their actual types?

Object.defineProperty(constants, name, {
value: replacementValue,
});
Expand Down
Loading