This commit is contained in:
Ben Irvin 2022-08-23 10:49:27 +02:00
parent da00ba89e1
commit 1cf0cb5c4c

View File

@ -1,6 +1,8 @@
'use strict';
const { ApplicationError } = require('@strapi/utils').errors;
const { YupValidationError } = require('@strapi/utils/lib/errors');
const { omit } = require('lodash');
const createContext = require('../../../../../../test/helpers/create-context');
const apiTokenController = require('../api-token');
@ -64,7 +66,7 @@ describe('API Token Controller', () => {
expect(created).toHaveBeenCalled();
});
test.only('Create API Token with lifespan', async () => {
test('Create API Token with lifespan', async () => {
const lifespan = 90 * 24 * 60 * 60 * 1000; // 90 days
const createBody = {
...body,
@ -72,7 +74,8 @@ describe('API Token Controller', () => {
};
const tokenBody = {
...createBody,
expirationDate: Date.now() + lifespan,
expiresAt: Date.now() + lifespan,
permissions: undefined,
};
const create = jest.fn().mockResolvedValue(tokenBody);
@ -94,9 +97,75 @@ describe('API Token Controller', () => {
await apiTokenController.create(ctx);
expect(exists).toHaveBeenCalledWith({ name: body.name });
expect(exists).toHaveBeenCalledWith({ name: tokenBody.name });
expect(badRequest).not.toHaveBeenCalled();
expect(create).toHaveBeenCalledWith(body);
expect(create).toHaveBeenCalledWith(createBody);
expect(created).toHaveBeenCalled();
});
test('Throws with invalid lifespan', async () => {
const lifespan = -1;
const createBody = {
...body,
lifespan,
};
const create = jest.fn();
const created = jest.fn();
const ctx = createContext({ body: createBody }, { created });
global.strapi = {
admin: {
services: {
'api-token': {
create,
},
},
},
};
expect(async () => {
await apiTokenController.create(ctx);
}).rejects.toThrow(YupValidationError);
expect(create).not.toHaveBeenCalled();
expect(created).not.toHaveBeenCalled();
});
test('Ignores a received expiresAt', async () => {
const lifespan = 90 * 24 * 60 * 60 * 1000; // 90 days
const createBody = {
...body,
expiresAt: 1234,
lifespan,
};
const tokenBody = {
...createBody,
expiresAt: Date.now() + lifespan,
permissions: undefined,
};
const create = jest.fn().mockResolvedValue(tokenBody);
const exists = jest.fn(() => false);
const badRequest = jest.fn();
const created = jest.fn();
const ctx = createContext({ body: createBody }, { badRequest, created });
global.strapi = {
admin: {
services: {
'api-token': {
exists,
create,
},
},
},
};
await apiTokenController.create(ctx);
expect(exists).toHaveBeenCalledWith({ name: tokenBody.name });
expect(badRequest).not.toHaveBeenCalled();
expect(create).toHaveBeenCalledWith(omit(createBody, 'expiresAt'));
expect(created).toHaveBeenCalled();
});
});