Skip to content

Commit

Permalink
test: enable more linter rules in tests (#13027)
Browse files Browse the repository at this point in the history
* chore: consistent return

* chore: no-var

* chore: no useless catch

* chore: prefer const
  • Loading branch information
sobolk authored Jul 28, 2023
1 parent c5b4ffa commit 806ed1d
Show file tree
Hide file tree
Showing 40 changed files with 79 additions and 84 deletions.
8 changes: 4 additions & 4 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,14 +114,14 @@ module.exports = {
'@typescript-eslint/no-inferrable-types': 'off',
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/no-unused-vars': 'off',
'consistent-return': 'off',
'consistent-return': 'error',
'import/no-extraneous-dependencies': 'off',
'no-constant-condition': 'off',
'no-restricted-syntax': 'off',
'no-useless-catch': 'off',
'no-useless-catch': 'error',
'no-useless-escape': 'off',
'no-var': 'off',
'prefer-const': 'off',
'no-var': 'error',
'prefer-const': 'error',
'spellcheck/spell-checker': 'off',
},
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export async function appSyncClient<ResponseDataType = unknown, VarsType = Recor
if (body.errors?.length) {
return reject(new Error(`GraphQL request error(s): ${JSON.stringify(body.errors)}`));
}
resolve(body.data);
return resolve(body.data);
})
.once('error', (err) => reject(err));
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ describe('websocket subscription', () => {

describe('onSubscribe', () => {
let subsServer: AppSyncSimulatorSubscriptionServer;
let asyncIterator = new PubSub().asyncIterator('onMessage');
const asyncIterator = new PubSub().asyncIterator('onMessage');
const tokenString = 'token-here';
const jwt = { iss: 'some issuer' };
const doc = parse(/* GraphQL */ `
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ describe('runSubscription', () => {
`);
let schema: GraphQLSchema;

let subscriptionResolver = jest.fn();
let subscriptionSubscribe = jest.fn();
const subscriptionResolver = jest.fn();
const subscriptionSubscribe = jest.fn();

const executionContext: AppSyncGraphQLExecutionContext = {
headers: { 'x-api-key': 'da-fake-key' },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { AmplifyAppSyncSimulatorAuthenticationType } from '../../../type-definit

const stubInfo = {} as unknown;
export const mockInfo = stubInfo as GraphQLResolveInfo;
var util;
let util;

beforeEach(() => {
const executionContext: AppSyncGraphQLExecutionContext = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { AmplifyAppSyncSimulatorAuthenticationType } from '../../../type-definit

const stubInfo = {} as unknown;
export const mockInfo = stubInfo as GraphQLResolveInfo;
var util;
let util;

beforeEach(() => {
const executionContext: AppSyncGraphQLExecutionContext = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { AppSyncGraphQLExecutionContext } from '../../../utils/graphql-runner';

const stubInfo = {} as unknown;
export const mockInfo = stubInfo as GraphQLResolveInfo;
var util;
let util;

beforeEach(() => {
const executionContext: AppSyncGraphQLExecutionContext = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const pluginInstance = {
const getOAuthObjectFromCognitoMock = getOAuthObjectFromCognito as jest.MockedFunction<typeof getOAuthObjectFromCognito>;

// mock context
let mockContext = {
const mockContext = {
amplify: {
getProjectConfig: jest.fn().mockReturnValue({
projectName: 'authHeadless',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ jest.mock('@aws-amplify/amplify-cli-core', () => {
...(jest.requireActual('@aws-amplify/amplify-cli-core') as {}),
FeatureFlags: {
getBoolean: jest.fn().mockImplementation((name, defaultValue) => {
if (name === 'auth.enableCaseInsensitivity') {
return true;
}
return name === 'auth.enableCaseInsensitivity';
}),
getNumber: jest.fn(),
getObject: jest.fn(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ jest.mock('../../walkthroughs/cloudformation-walkthrough');
jest.mock('@aws-amplify/amplify-cli-core');
jest.mock('@aws-amplify/amplify-prompts');

let mockAmplifyMeta = {
const mockAmplifyMeta = {
custom: {
mockcdkresourcename: {
service: CDK_SERVICE_NAME,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pathManager.getBackendDirPath = jest.fn().mockReturnValue('mockTargetDir');
(JSONUtilities.writeJson = jest.fn()), (JSONUtilities.readJson = jest.fn());

const buildCustomResources_mock = buildCustomResources as jest.MockedFunction<typeof buildCustomResources>;
let customResourceNameQuestion_mock = customResourceNameQuestion as jest.MockedFunction<typeof customResourceNameQuestion>;
const customResourceNameQuestion_mock = customResourceNameQuestion as jest.MockedFunction<typeof customResourceNameQuestion>;
customResourceNameQuestion_mock.mockResolvedValue('customresoourcename');

describe('addCDKWalkthrough scenarios', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jest.mock('fs-extra', () => ({

pathManager.getBackendDirPath = jest.fn().mockReturnValue('mockTargetDir');

let customResourceNameQuestion_mock = customResourceNameQuestion as jest.MockedFunction<typeof customResourceNameQuestion>;
const customResourceNameQuestion_mock = customResourceNameQuestion as jest.MockedFunction<typeof customResourceNameQuestion>;
customResourceNameQuestion_mock.mockResolvedValue('customresoourcename');

describe('addCFNWalkthrough scenarios', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ describe('test layer CFN generation functions', () => {
});

it('should generate the expected CFN for an existing LL version and new version with complex permissions', () => {
let permissions: LayerPermission[] = [
const permissions: LayerPermission[] = [
{ type: PermissionEnum.Private },
{ type: PermissionEnum.AwsAccounts, accounts: ['123456789012', '098765432112'] },
{ type: PermissionEnum.AwsOrg, orgs: ['o-123456789012', 'o-098765432112'] },
Expand All @@ -129,7 +129,7 @@ describe('test layer CFN generation functions', () => {

it('should generate the expected CFN for an existing LL version and new version with public permission', () => {
// Public should override other permissions
let permissions: LayerPermission[] = [
const permissions: LayerPermission[] = [
{ type: PermissionEnum.Private },
{ type: PermissionEnum.AwsAccounts, accounts: ['123456789012', '098765432112'] },
{ type: PermissionEnum.AwsOrg, orgs: ['o-123456789012', 'o-098765432112'] },
Expand Down
4 changes: 2 additions & 2 deletions packages/amplify-category-hosting/__tests__/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ describe('index', () => {
const ANOTHERSERVICE = 'AnotherHostingService';

const mockAvailableServices = [];
let mockDisabledServices = [];
let mockEnabledServices = [];
const mockDisabledServices = [];
const mockEnabledServices = [];

const mockAnswers = {
selectedServices: [],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ describe('update ddb walkthrough tests', () => {
});

it('updateWalkthrough() test to add gsi', async () => {
let mockAmplifyMeta = {
const mockAmplifyMeta = {
storage: {
mockresourcename: {
service: 'DynamoDB',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ describe('add s3 walkthrough tests', () => {

stateManager.getMeta = jest.fn().mockReturnValue(S3MockDataBuilder.mockAmplifyMeta);

let options = {};
const options = {};
const returnedResourcename = await addWalkthrough(mockContext, S3MockDataBuilder.mockFilePath, mockContext, options);

expect(returnedResourcename).toEqual(S3MockDataBuilder.mockResourceName);
Expand Down Expand Up @@ -126,7 +126,7 @@ describe('add s3 walkthrough tests', () => {

stateManager.getMeta = jest.fn().mockReturnValue(S3MockDataBuilder.mockAmplifyMeta);

let options = {};
const options = {};
const returnedResourcename = await addWalkthrough(mockContext, S3MockDataBuilder.mockFilePath, mockContext, options);

expect(returnedResourcename).toEqual(S3MockDataBuilder.mockResourceName);
Expand Down Expand Up @@ -160,7 +160,7 @@ describe('add s3 walkthrough tests', () => {

stateManager.getMeta = jest.fn().mockReturnValue(S3MockDataBuilder.mockAmplifyMeta);

let options = {};
const options = {};
const returnedResourcename = await addWalkthrough(mockContext, S3MockDataBuilder.mockFilePath, mockContext, options);

expect(returnedResourcename).toEqual(S3MockDataBuilder.mockResourceName);
Expand Down Expand Up @@ -202,7 +202,7 @@ describe('add s3 walkthrough tests', () => {

stateManager.getMeta = jest.fn().mockReturnValue(S3MockDataBuilder.mockAmplifyMeta);

let options = {};
const options = {};
const returnedResourcename = await addWalkthrough(mockContext, S3MockDataBuilder.mockFilePath, mockContext, options);

expect(returnedResourcename).toEqual(S3MockDataBuilder.mockResourceName);
Expand Down
31 changes: 13 additions & 18 deletions packages/amplify-cli-core/src/__tests__/help.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,42 +148,42 @@ describe('amplify help functions: ', () => {
];

it('lookup valid command (init) and expect not null', () => {
let initCommandInfo = lookUpCommand(mockCommandsInfo, 'init');
const initCommandInfo = lookUpCommand(mockCommandsInfo, 'init');
expect(initCommandInfo).not.toBeUndefined();
});

it('lookup invalid command and expect null', () => {
let invalidCommandInfo = lookUpCommand(mockCommandsInfo, 'invalidcommand');
const invalidCommandInfo = lookUpCommand(mockCommandsInfo, 'invalidcommand');
expect(invalidCommandInfo).toBeUndefined();
});

it('lookup valid command (init) and expect correct command name', () => {
let initCommandInfo = lookUpCommand(mockCommandsInfo, 'init');
const initCommandInfo = lookUpCommand(mockCommandsInfo, 'init');
expect(initCommandInfo!.command).toBe('init');
});

it('lookup valid command (configure) and expect correct command name', () => {
let initCommandInfo = lookUpCommand(mockCommandsInfo, 'configure');
const initCommandInfo = lookUpCommand(mockCommandsInfo, 'configure');
expect(initCommandInfo!.command).toBe('configure');
});

it('lookup valid subcommand (configure project) and expect not null', () => {
let configureProjectSubCommandInfo = lookUpSubcommand(mockCommandsInfo, 'configure', 'project');
const configureProjectSubCommandInfo = lookUpSubcommand(mockCommandsInfo, 'configure', 'project');
expect(configureProjectSubCommandInfo).not.toBeUndefined();
});

it('lookup invalid subcommand and expect null', () => {
let invalidSubCommandInfo = lookUpSubcommand(mockCommandsInfo, 'invalidcommand', 'invalidsubcommand');
const invalidSubCommandInfo = lookUpSubcommand(mockCommandsInfo, 'invalidcommand', 'invalidsubcommand');
expect(invalidSubCommandInfo).toBeUndefined();
});

it('lookup valid subcommand (configure project) and expect correct subcommand name', () => {
let configureProjectSubCommandInfo = lookUpSubcommand(mockCommandsInfo, 'configure', 'project');
const configureProjectSubCommandInfo = lookUpSubcommand(mockCommandsInfo, 'configure', 'project');
expect(configureProjectSubCommandInfo!.subCommand).toBe('project');
});

it('lookup valid subcommand (configure hosting) correct subcommand name', () => {
let configureHostingSubCommandInfo = lookUpSubcommand(mockCommandsInfo, 'configure', 'hosting');
const configureHostingSubCommandInfo = lookUpSubcommand(mockCommandsInfo, 'configure', 'hosting');
expect(configureHostingSubCommandInfo!.subCommand).toBe('hosting');
});

Expand All @@ -195,7 +195,7 @@ describe('amplify help functions: ', () => {
plugin: 'core',
subCommands: ['configure'],
};
let specifiedCommands = parseHelpCommands(configureInput, mockCommandsInfo);
const specifiedCommands = parseHelpCommands(configureInput, mockCommandsInfo);
expect(specifiedCommands.command).toBe('configure');
expect(specifiedCommands.subCommand).toBe('');
});
Expand All @@ -208,14 +208,13 @@ describe('amplify help functions: ', () => {
options: { help: true, yes: false },
subCommands: ['mock', 'function'],
};
let specifiedCommands = parseHelpCommands(mockFunctionInput, mockCommandsInfo);
const specifiedCommands = parseHelpCommands(mockFunctionInput, mockCommandsInfo);
expect(specifiedCommands.command).toBe('mock');
expect(specifiedCommands.subCommand).toBe('function');
});

it('run help invalid command', () => {
let mockContext: $TSContext;
mockContext = {
const mockContext = {
input: {
argv: ['node', 'amplify', 'invalid', 'command', '-h'],
command: 'help',
Expand All @@ -230,9 +229,7 @@ describe('amplify help functions: ', () => {
});

it('run help command (mock)', () => {
let mockContext: $TSContext;

mockContext = {
const mockContext = {
print: {
info: jest.fn(),
},
Expand All @@ -249,9 +246,7 @@ describe('amplify help functions: ', () => {
});

it('run help subcommand (mock function)', () => {
let mockContext: $TSContext;

mockContext = {
const mockContext = {
print: {
info: jest.fn(),
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ jest.mock('which', () => ({
if (runtimeName === 'python3') return pathToPython3Runtime;
if (runtimeName === 'python') return pathToPythonRuntime;
if (runtimeName === 'node') return pathToNodeRuntime;
throw new Error('unknown runtime');
}),
}));
jest.mock('fs-extra', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ execa_mock.command.mockResolvedValue({} as any);
jest.mock('fs-extra');
const fs_mock = fs as jest.Mocked<typeof fs>;

let userConfirmation = true;
const userConfirmation = true;
const context_stub = {
amplify: {
confirmPrompt: async () => userConfirmation,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,18 +42,14 @@ describe('amplify console add hosting', () => {

// Manual tests
it('add / publish / configure/ serve /remove hosting for manual deployment should succeed', async () => {
try {
await addManualHosting(projRoot);
expect(fs.existsSync(path.join(projRoot, 'amplify', 'backend', 'hosting', 'amplifyhosting'))).toBe(true);
const type = loadTypeFromTeamProviderInfo(projRoot, ORIGINAL_ENV);
expect(type).toBe(TYPE_MANUAL);
npmInstall(projRoot);
await amplifyPublish(projRoot);
await removeHosting(projRoot);
await amplifyPush(projRoot);
} catch (err) {
throw err;
}
await addManualHosting(projRoot);
expect(fs.existsSync(path.join(projRoot, 'amplify', 'backend', 'hosting', 'amplifyhosting'))).toBe(true);
const type = loadTypeFromTeamProviderInfo(projRoot, ORIGINAL_ENV);
expect(type).toBe(TYPE_MANUAL);
npmInstall(projRoot);
await amplifyPublish(projRoot);
await removeHosting(projRoot);
await amplifyPush(projRoot);
});

it('when hosting is enabled, add new env should be able to deploy frontend successfully', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ describe('amplify console build', () => {
const originalProjectDirPath = await util.createNewProjectDir('console-original');
await headlessInit(originalProjectDirPath, amplifyParam, providersParam, codegenParam);
expect(checkAmplifyFolderStructure(originalProjectDirPath)).toBeTruthy();
let originalTeamProviderInfo = getTeamProviderInfo(originalProjectDirPath);
const originalTeamProviderInfo = getTeamProviderInfo(originalProjectDirPath);
expect(originalTeamProviderInfo).toBeDefined();
expect(originalTeamProviderInfo['devteama']).toBeDefined();

Expand All @@ -153,7 +153,7 @@ describe('amplify console build', () => {
};
await headlessInit(clonedProjectDirPath, amplifyParam, providersParam, codegenParam);
expect(checkAmplifyFolderStructure(clonedProjectDirPath)).toBeTruthy();
let clonedTeamProviderInfo = getTeamProviderInfo(clonedProjectDirPath);
const clonedTeamProviderInfo = getTeamProviderInfo(clonedProjectDirPath);
expect(clonedTeamProviderInfo).toBeDefined();
expect(clonedTeamProviderInfo['devteamb']).toBeDefined();

Expand Down
2 changes: 1 addition & 1 deletion packages/amplify-e2e-core/failed-test-reporter.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class FailedTestNameReporter {
getFailedTestRegEx(results) {
let failedTestNames = [];
if (results.testResults) {
for (let result of results.testResults) {
for (const result of results.testResults) {
failedTestNames = [...failedTestNames, ...this.getFailedTestRegEx(result)];
}
} else if (results.status === 'failed') {
Expand Down
4 changes: 2 additions & 2 deletions packages/amplify-e2e-core/src/nexpect-reporter.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,8 @@ class AmplifyCLIExecutionReporter {
}),
);
}
let sanitizedSections = [];
for (let section of commandAndParams) {
const sanitizedSections = [];
for (const section of commandAndParams) {
// this ensures only alphanumeric values are in the file name
sanitizedSections.push(section.replace(/[^a-z0-9]/gi, '_').toLowerCase());
}
Expand Down
2 changes: 1 addition & 1 deletion packages/amplify-e2e-tests/functions/s3-list-objects.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const awsS3Client = new AWS.S3();
const bucketEnvVar = '{{bucketEnvVar}}'; // This value is replaced from test

exports.handler = async () => {
let listObjects = await awsS3Client
const listObjects = await awsS3Client
.listObjectsV2({
Bucket: process.env[bucketEnvVar],
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ describe('auth import identity pool and userpool', () => {
await initJSProjectWithProfile(projectRoot, projectSettings);
await importIdentityPoolAndUserPool(projectRoot, ogSettings.userPoolName, { native: '_app_client ', web: '_app_clientWeb' });

let projectDetails = getAuthProjectDetails(projectRoot);
const projectDetails = getAuthProjectDetails(projectRoot);

expectAuthProjectDetailsMatch(projectDetails, ogProjectDetails);

Expand Down
Loading

0 comments on commit 806ed1d

Please sign in to comment.