Small clean-up after Jest to Vitest switch in API (#16462)

Co-authored-by: Rijk van Zanten <rijkvanzanten@me.com>
This commit is contained in:
Pascal Jufer
2022-11-15 23:20:45 +01:00
committed by GitHub
parent e79720735a
commit 45eb4941fc
13 changed files with 86 additions and 120 deletions

View File

@@ -1,14 +1,11 @@
// @ts-nocheck
import { multipartHandler } from './files';
import { InvalidPayloadException } from '../exceptions/invalid-payload';
import { PassThrough } from 'stream';
import FormData from 'form-data';
import { vi, describe, expect, it } from 'vitest';
import { Request, Response } from 'express';
vi.mock('../../src/cache');
vi.mock('../../src/database');
vi.mock('../../src/utils/validate-env');
describe('multipartHandler', () => {
it(`Errors out if request doesn't contain any files to upload`, () => {
@@ -21,13 +18,14 @@ describe('multipartHandler', () => {
is: vi.fn().mockReturnValue(true),
body: fakeForm.getBuffer(),
params: {},
pipe: (input) => stream.pipe(input),
};
pipe: (input: NodeJS.WritableStream) => stream.pipe(input),
} as unknown as Request;
const res = {} as Response;
const stream = new PassThrough();
stream.push(fakeForm.getBuffer());
multipartHandler(req, {}, (err) => {
multipartHandler(req, res, (err) => {
expect(err.message).toBe('No files where included in the body');
expect(err).toBeInstanceOf(InvalidPayloadException);
});
@@ -48,13 +46,14 @@ describe('multipartHandler', () => {
is: vi.fn().mockReturnValue(true),
body: fakeForm.getBuffer(),
params: {},
pipe: (input) => stream.pipe(input),
};
pipe: (input: NodeJS.WritableStream) => stream.pipe(input),
} as unknown as Request;
const res = {} as Response;
const stream = new PassThrough();
stream.push(fakeForm.getBuffer());
multipartHandler(req, {}, (err) => {
multipartHandler(req, res, (err) => {
expect(err.message).toBe('File is missing filename');
expect(err).toBeInstanceOf(InvalidPayloadException);
});

View File

@@ -1,14 +1,14 @@
import knex, { Knex } from 'knex';
import { getTracker, MockClient, Tracker } from 'knex-mock-client';
import run from './run';
import { describe, beforeAll, afterEach, it, expect } from 'vitest';
import { describe, beforeAll, afterEach, it, expect, MockedFunction, vi } from 'vitest';
describe('run', () => {
let db: Knex;
let db: MockedFunction<Knex>;
let tracker: Tracker;
beforeAll(() => {
db = knex({ client: MockClient });
db = vi.mocked(knex({ client: MockClient }));
tracker = getTracker();
});

View File

@@ -1,5 +1,3 @@
// @ts-nocheck
import jwt from 'jsonwebtoken';
import getDatabase from '../database';
import emitter from '../emitter';
@@ -8,6 +6,8 @@ import { InvalidCredentialsException } from '../exceptions';
import { handler } from './authenticate';
import '../../src/types/express.d.ts';
import { vi, afterEach, test, expect } from 'vitest';
import { Request, Response } from 'express';
import { Knex } from 'knex';
vi.mock('../../src/database');
vi.mock('../../src/env', () => ({
@@ -24,9 +24,8 @@ test('Short-circuits when authenticate filter is used', async () => {
const req = {
ip: '127.0.0.1',
get: vi.fn(),
};
const res = {};
} as unknown as Request;
const res = {} as Response;
const next = vi.fn();
const customAccountability = { admin: true };
@@ -52,12 +51,11 @@ test('Uses default public accountability when no token is given', async () => {
return null;
}
}),
};
const res = {};
} as unknown as Request;
const res = {} as Response;
const next = vi.fn();
vi.spyOn(emitter, 'emitFilter').mockImplementation((_, payload) => payload);
vi.spyOn(emitter, 'emitFilter').mockImplementation(async (_, payload) => payload);
await handler(req, res, next);
@@ -111,9 +109,8 @@ test('Sets accountability to payload contents if valid token is passed', async (
}
}),
token,
};
const res = {};
} as unknown as Request;
const res = {} as Response;
const next = vi.fn();
await handler(req, res, next);
@@ -172,7 +169,7 @@ test('Throws InvalidCredentialsException when static token is used, but user doe
leftJoin: vi.fn().mockReturnThis(),
where: vi.fn().mockReturnThis(),
first: vi.fn().mockResolvedValue(undefined),
});
} as unknown as Knex);
const req = {
ip: '127.0.0.1',
@@ -187,9 +184,8 @@ test('Throws InvalidCredentialsException when static token is used, but user doe
}
}),
token: 'static-token',
};
const res = {};
} as unknown as Request;
const res = {} as Response;
const next = vi.fn();
expect(handler(req, res, next)).rejects.toEqual(new InvalidCredentialsException());
@@ -210,9 +206,8 @@ test('Sets accountability to user information when static token is used', async
}
}),
token: 'static-token',
};
const res = {};
} as unknown as Request;
const res = {} as Response;
const next = vi.fn();
const testUser = { id: 'test-id', role: 'test-role', admin_access: true, app_access: false };
@@ -233,7 +228,7 @@ test('Sets accountability to user information when static token is used', async
leftJoin: vi.fn().mockReturnThis(),
where: vi.fn().mockReturnThis(),
first: vi.fn().mockResolvedValue(testUser),
});
} as unknown as Knex);
await handler(req, res, next);
@@ -242,16 +237,16 @@ test('Sets accountability to user information when static token is used', async
// Test for 0 / 1 instead of false / true
next.mockClear();
testUser.admin_access = 1;
testUser.app_access = 0;
testUser.admin_access = 1 as never;
testUser.app_access = 0 as never;
await handler(req, res, next);
expect(req.accountability).toEqual(expectedAccountability);
expect(next).toHaveBeenCalledTimes(1);
// Test for "1" / "0" instead of true / false
next.mockClear();
testUser.admin_access = '0';
testUser.app_access = '1';
testUser.admin_access = '0' as never;
testUser.app_access = '1' as never;
expectedAccountability.admin = false;
expectedAccountability.app = true;
await handler(req, res, next);

View File

@@ -5,14 +5,11 @@ import { afterEach, beforeAll, beforeEach, describe, expect, it, MockedFunction,
import { FieldsService } from '.';
import { InvalidPayloadException } from '../exceptions';
vi.mock('../../src/database/index', () => {
return {
__esModule: true,
default: vi.fn(),
getDatabaseClient: vi.fn().mockReturnValue('postgres'),
getSchemaInspector: vi.fn(),
};
});
vi.mock('../../src/database/index', () => ({
default: vi.fn(),
getDatabaseClient: vi.fn().mockReturnValue('postgres'),
getSchemaInspector: vi.fn(),
}));
describe('Integration Tests', () => {
let db: MockedFunction<Knex>;

View File

@@ -3,20 +3,16 @@ import knex, { Knex } from 'knex';
import { MockClient, Tracker, getTracker } from 'knex-mock-client';
import { FilesService, ItemsService } from '.';
import { InvalidPayloadException } from '../exceptions';
import { describe, beforeAll, afterEach, expect, it, vi, beforeEach, SpyInstance } from 'vitest';
import { describe, beforeAll, afterEach, expect, it, vi, beforeEach, MockedFunction, SpyInstance } from 'vitest';
vi.mock('exifr');
vi.mock('../../src/database/index', () => {
return { getDatabaseClient: vi.fn().mockReturnValue('postgres') };
});
vi.mock('../../src/database/index');
describe('Integration Tests', () => {
let db: Knex;
let db: MockedFunction<Knex>;
let tracker: Tracker;
beforeAll(async () => {
db = knex({ client: MockClient });
beforeAll(() => {
db = vi.mocked(knex({ client: MockClient }));
tracker = getTracker();
});

View File

@@ -2,7 +2,7 @@ import { Query } from '@directus/shared/types';
import knex, { Knex } from 'knex';
import { getTracker, MockClient, Tracker } from 'knex-mock-client';
import { cloneDeep } from 'lodash';
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import { afterEach, beforeAll, describe, expect, it, vi, MockedFunction } from 'vitest';
import { ItemsService } from '../../src/services';
import { InvalidPayloadException } from '../exceptions';
import { sqlFieldFormatter, sqlFieldList } from '../__utils__/items-utils';
@@ -19,25 +19,24 @@ vi.mock('../env', async () => {
};
});
vi.mock('../../src/database/index', () => {
return { default: vi.fn(), getDatabaseClient: vi.fn().mockReturnValue('postgres') };
});
vi.mock('../../src/database/index', () => ({
default: vi.fn(),
getDatabaseClient: vi.fn().mockReturnValue('postgres'),
}));
vi.mock('../cache', () => {
return {
getCache: vi.fn().mockReturnValue({
cache: {
clear: vi.fn(),
},
systemCache: {
clear: vi.fn(),
},
}),
};
});
vi.mock('../cache', () => ({
getCache: vi.fn().mockReturnValue({
cache: {
clear: vi.fn(),
},
systemCache: {
clear: vi.fn(),
},
}),
}));
describe('Integration Tests', () => {
let db: Knex;
let db: MockedFunction<Knex>;
let tracker: Tracker;
const schemas: Record<string, any> = {
@@ -45,8 +44,8 @@ describe('Integration Tests', () => {
user: { schema: userSchema, tables: Object.keys(userSchema.collections) },
};
beforeAll(async () => {
db = knex({ client: MockClient });
beforeAll(() => {
db = vi.mocked(knex({ client: MockClient }));
tracker = getTracker();
});
@@ -1049,7 +1048,7 @@ describe('Integration Tests', () => {
// intentional `as any` to test non-array data on runtime
await itemsService.updateBatch(items[0] as any);
} catch (err) {
expect(err.message).toBe(`Input should be an array of items.`);
expect((err as Error).message).toBe(`Input should be an array of items.`);
expect(err).toBeInstanceOf(InvalidPayloadException);
}
}

View File

@@ -1,15 +1,11 @@
import { afterEach, beforeEach, describe, expect, it, SpyInstance, vi } from 'vitest';
import { ItemsService, NotificationsService } from '.';
vi.mock('../../src/env', async () => ({
...(await vi.importActual<any>('../../src/env')),
PUBLIC_URL: '/',
vi.mock('../../src/database/index', () => ({
default: vi.fn(),
getDatabaseClient: vi.fn().mockReturnValue('postgres'),
}));
vi.mock('../../src/database/index', () => {
return { __esModule: true, default: vi.fn(), getDatabaseClient: vi.fn().mockReturnValue('postgres') };
});
describe('Integration Tests', () => {
describe('Services / Notifications', () => {
let service: NotificationsService;

View File

@@ -2,19 +2,18 @@ import knex, { Knex } from 'knex';
import { MockClient, Tracker, getTracker } from 'knex-mock-client';
import { PayloadService } from '../../src/services';
import { getHelpers, Helpers } from '../../src/database/helpers';
import { describe, beforeAll, afterEach, it, expect, vi, beforeEach } from 'vitest';
import { describe, beforeAll, afterEach, it, expect, vi, beforeEach, MockedFunction } from 'vitest';
vi.mock('../../src/database/index', () => {
return { getDatabaseClient: vi.fn().mockReturnValue('postgres') };
});
vi.mock('../../src/database/index');
vi.mock('../../src/database/index', () => ({
getDatabaseClient: vi.fn().mockReturnValue('postgres'),
}));
describe('Integration Tests', () => {
let db: Knex;
let db: MockedFunction<Knex>;
let tracker: Tracker;
beforeAll(async () => {
db = knex({ client: MockClient });
db = vi.mocked(knex({ client: MockClient }));
tracker = getTracker();
});
@@ -187,8 +186,8 @@ describe('Integration Tests', () => {
});
describe('processes dates', () => {
it('with zero values', async () => {
const result = await service.processDates(
it('with zero values', () => {
const result = service.processDates(
[
{
[dateFieldId]: '0000-00-00',
@@ -208,8 +207,8 @@ describe('Integration Tests', () => {
]);
});
it('with typical values', async () => {
const result = await service.processDates(
it('with typical values', () => {
const result = service.processDates(
[
{
[dateFieldId]: '2022-01-10',
@@ -228,8 +227,8 @@ describe('Integration Tests', () => {
]);
});
it('with date object values', async () => {
const result = await service.processDates(
it('with date object values', () => {
const result = service.processDates(
[
{
[dateFieldId]: new Date(1666777777000),

View File

@@ -1,25 +1,16 @@
import knex, { Knex } from 'knex';
import { getTracker, MockClient, Tracker } from 'knex-mock-client';
import { CollectionsService, FieldsService, RelationsService, SpecificationService } from '../../src/services';
import { describe, beforeAll, afterEach, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/database/index', async () => {
const actual = await vi.importActual('@directus/shared/utils/node');
return {
...(actual as object),
getDatabaseClient: vi.fn().mockReturnValue('postgres'),
};
});
import { describe, beforeAll, afterEach, it, expect, vi, beforeEach, MockedFunction } from 'vitest';
class Client_PG extends MockClient {}
describe('Integration Tests', () => {
let db: Knex;
let db: MockedFunction<Knex>;
let tracker: Tracker;
beforeAll(async () => {
db = knex({ client: Client_PG });
db = vi.mocked(knex({ client: Client_PG }));
tracker = getTracker();
});

View File

@@ -5,9 +5,10 @@ import { afterEach, beforeAll, describe, it, vi, expect, MockedFunction } from '
import { ItemsService, UsersService } from '.';
import { InvalidPayloadException } from '../exceptions';
vi.mock('../../src/database/index', () => {
return { __esModule: true, default: vi.fn(), getDatabaseClient: vi.fn().mockReturnValue('postgres') };
});
vi.mock('../../src/database/index', () => ({
default: vi.fn(),
getDatabaseClient: vi.fn().mockReturnValue('postgres'),
}));
const testSchema = {
collections: {

View File

@@ -12,23 +12,16 @@ import {
snapshotBeforeDeleteCollection,
} from '../__utils__/snapshots';
import { Snapshot } from '../types';
import { describe, afterEach, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/database/index', () => {
return {
getDatabaseClient: vi.fn().mockReturnValue('postgres'),
};
});
vi.mock('../../src/database/index');
import { describe, afterEach, it, expect, vi, beforeEach, MockedFunction } from 'vitest';
class Client_PG extends MockClient {}
describe('applySnapshot', () => {
let db: Knex;
let db: MockedFunction<Knex>;
let tracker: Tracker;
beforeEach(() => {
db = knex({ client: Client_PG });
db = vi.mocked(knex({ client: Client_PG }));
tracker = getTracker();
});

View File

@@ -62,7 +62,7 @@ test('Returns o2m', () => {
expect(result).toBe('o2m');
});
test('Returns null when field/collection doesnt match the relationship', () => {
test('Returns null when field/collection does not match the relationship', () => {
const relation = {
collection: 'articles',
field: 'author',

View File

@@ -13,5 +13,5 @@
"declaration": true,
"resolveJsonModule": true
},
"exclude": ["node_modules", "dist", "extensions", "**/__utils__/*.*", "**/__mocks__/*.*", "**/*.test.ts"]
"exclude": ["node_modules", "dist", "extensions"]
}