Skip to content

Commit

Permalink
#11 fix sonar-issues, unit-tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ga-ebp committed Apr 9, 2024
1 parent fdb75bd commit 5035bea
Show file tree
Hide file tree
Showing 11 changed files with 243 additions and 7 deletions.
1 change: 1 addition & 0 deletions apps/server-asset-sg/jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,5 @@ export default {
},
moduleFileExtensions: ['ts', 'js', 'html'],
coverageDirectory: '../../coverage/apps/server-asset-sg',
coverageReporters: ['json', 'text', 'cobertura', 'lcov'],
};
3 changes: 2 additions & 1 deletion apps/server-asset-sg/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,8 @@
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
"options": {
"jestConfig": "apps/server-asset-sg/jest.config.ts",
"passWithNoTests": true
"passWithNoTests": true,
"codeCoverage": true
}
},
"gen-prisma-client": {
Expand Down
107 changes: 107 additions & 0 deletions apps/server-asset-sg/src/app/contact-edit/contact-edit.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { Test, TestingModule } from '@nestjs/testing';
import { left, right } from 'fp-ts/Either';

import { Contact, PatchContact } from '@asset-sg/shared';

import { PrismaService } from '../prisma/prisma.service';

import { ContactEditService } from './contact-edit.service';


jest.mock('../prisma/prisma.service');

const mockPatchContact: PatchContact = {
name: 'John Doe',
street: '123 Main Street',
houseNumber: '1A',
plz: '12345',
locality: 'City',
country: 'Country',
telephone: '123-456-7890',
email: 'john.doe@example.com',
website: 'www.example.com',
contactKindItemCode: '123'
};
const mockContact: Contact = {
id: 1,
contactKindItemCode: '123',
name: 'John Doe',
street: '123 Main Street',
houseNumber: '1A',
plz: '12345',
locality: 'City',
country: 'Country',
telephone: '123-456-7890',
email: 'john.doe@example.com',
website: 'www.example.com'
};

const mockPrisma = {
contact: {}
};


describe('ContactEditService', () => {
let service: ContactEditService;
let prismaService: PrismaService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
ContactEditService,
{
provide: PrismaService,
useValue: mockPrisma,
},
],
}).compile();

service = module.get<ContactEditService>(ContactEditService);
prismaService = module.get<PrismaService>(PrismaService);

});

it('should be defined', () => {
expect(service).toBeDefined();
});

it('should create a contact', async () => {
prismaService.contact.create = jest.fn().mockResolvedValue(mockContact);

const result = await service.createContact(mockPatchContact)();

expect(result).toEqual(right(mockContact));
expect(prismaService.contact.create).toHaveBeenCalledWith({ data: mockPatchContact });
});

it('should update a contact', async () => {
const mockContactId = 1;

prismaService.contact.update = jest.fn().mockResolvedValue(mockPatchContact);
prismaService.contact.findFirstOrThrow = jest.fn().mockResolvedValue(mockContact);

const result = await service.updateContact(mockContactId, mockContact)();

expect(result).toEqual(right(mockContact));
expect(prismaService.contact.update).toHaveBeenCalledWith({ where: { contactId: mockContactId }, data: mockContact });
});

it('should handle errors when creating a contact', async () => {
prismaService.contact.create = jest.fn().mockRejectedValue(new Error('Test error'));

const result = await service.createContact(mockContact)();

expect(result).toEqual(left(new Error()));
expect(prismaService.contact.create).toHaveBeenCalledWith({ data: mockContact });
});

it('should handle errors when updating a contact', async () => {
const mockContactId = 1;
prismaService.contact.update = jest.fn().mockRejectedValue(new Error('Test error'));

const result = await service.updateContact(mockContactId, mockContact)();

expect(result).toEqual(left(new Error()));
expect(prismaService.contact.update).toHaveBeenCalledWith({ where: { contactId: mockContactId }, data: mockContact });
});
});
1 change: 0 additions & 1 deletion development/init/elasticsearch/index
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
PUT /swissgeol_asset_asset


PUT /swissgeol_asset_asset/_mapping
{
"properties": {
Expand Down
2 changes: 1 addition & 1 deletion libs/asset-editor/jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export default {
transform: {
'^.+\\.(ts|mjs|js|html)$': 'jest-preset-angular',
},
transformIgnorePatterns: ['node_modules/(?!.*\\.mjs$)'],
transformIgnorePatterns: ['node_modules/(?!.*\\.mjs$|ol)'],
snapshotSerializers: [
'jest-preset-angular/build/serializers/no-ng-attributes',
'jest-preset-angular/build/serializers/ng-snapshot',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
</ng-container>
</div>
<table class="asset-details">
<caption></caption>
<tr>
<th translate="search.file" class="icon-height"></th>
<td>
Expand Down Expand Up @@ -173,6 +174,7 @@
<td>
<ng-container *ngIf="rdAssetDetail.value.statusWorks.length === 0">&ndash;</ng-container>
<table class="status-works">
<caption></caption>
<tr *rxFor="let statusWork of rdAssetDetail.value.statusWorks">
<th>{{ statusWork.statusWorkDate | assetSgDate }}</th>
<td>{{ statusWork.statusWork | valueItemName }}</td>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@
background-color: #87d7e6;
color: #357183;
}
&:active:not(focus) {
&:active:not(:focus) {
box-shadow: none;
background-color: variables.$cyan-06;
color: variables.$white;
Expand Down Expand Up @@ -110,7 +110,7 @@
&:focus {
color: variables.$red;
}
&:active:not(focus) {
&:active:not(:focus) {
color: variables.$dark-red;
}
}
Expand All @@ -135,7 +135,7 @@
&:focus {
color: variables.$red;
}
&:active:not(focus) {
&:active:not(:focus) {
color: variables.$dark-red;
}
}
Expand Down
17 changes: 17 additions & 0 deletions libs/core/src/lib/ngrx-store-logger/ngrx-store-logger.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { ActionReducer } from '@ngrx/store';

import { storeLogger } from './ngrx-store-logger';

describe('storeLogger', () => {

it('should log state and action', () => {
const consoleLogSpy = jest.spyOn(console, 'log').mockImplementation(() => { /* noop */ });
const metaReducer = storeLogger<string>();
const actionReducer: ActionReducer<string, any> = (state: string | undefined, action: any) => { return state || ''; };

Check warning on line 10 in libs/core/src/lib/ngrx-store-logger/ngrx-store-logger.spec.ts

View workflow job for this annotation

GitHub Actions / Build and run tests

Unexpected any. Specify a different type

Check warning on line 10 in libs/core/src/lib/ngrx-store-logger/ngrx-store-logger.spec.ts

View workflow job for this annotation

GitHub Actions / Build and run tests

'action' is defined but never used

Check warning on line 10 in libs/core/src/lib/ngrx-store-logger/ngrx-store-logger.spec.ts

View workflow job for this annotation

GitHub Actions / Build and run tests

Unexpected any. Specify a different type

metaReducer(actionReducer)('state', { type: 'test' });

expect(consoleLogSpy).toHaveBeenCalled();
});

});
68 changes: 68 additions & 0 deletions libs/core/src/lib/serialize-error/serialize-error.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { NonError, deserializeError, isErrorLike, serializeError} from './serialize-error';

describe('serializeError', () => {
it('should serialize error objects', () => {
const error = new Error('Test error');
const serialized = serializeError(error);
expect(serialized).toHaveProperty('name', 'Error');
expect(serialized).toHaveProperty('message', 'Test error');
expect(serialized).toHaveProperty('stack');
});

it('should serialize non-error objects', () => {
const obj = { key: 'value' };
const serialized = serializeError(obj);
expect(serialized).toEqual(obj);
});

it('should serialize primitive values', () => {
expect(serializeError('test')).toBe('test');
expect(serializeError(123)).toBe(123);
});
});

describe('deserializeError', () => {
it('should deserialize serialized error objects', () => {
const error = new Error('Test error');
const serialized = serializeError(error);
const deserialized = deserializeError(serialized);
expect(deserialized).toBeInstanceOf(Error);
expect(deserialized.message).toBe('Test error');
});

it('should return NonError for non-error objects', () => {
const obj = { key: 'value' };
const deserialized = deserializeError(obj);
expect(deserialized).toBeInstanceOf(NonError);
expect(deserialized.message).toBe(JSON.stringify(obj));
});

it('should return NonError for primitive string', () => {
const deserialized = deserializeError('test');
expect(deserialized).toBeInstanceOf(NonError);
expect(deserialized.message).toBe('"test"');
});

it('should return NonError for primitive number', () => {
const deserialized = deserializeError(123);
expect(deserialized).toBeInstanceOf(NonError);
expect(deserialized.message).toBe('123');
});
});

describe('isErrorLike', () => {
it('should return true for error objects', () => {
const error = new Error('Test error');
expect(isErrorLike(error)).toBe(true);
});

it('should return false for non-error objects', () => {
const obj = { key: 'value' };
expect(isErrorLike(obj)).toBe(false);
});

it('should return false for primitive values', () => {
expect(isErrorLike('test')).toBe(false);
expect(isErrorLike(123)).toBe(false);
});
});
40 changes: 40 additions & 0 deletions libs/favourite/src/lib/services/favourite.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';

import { Favourite, FavouriteService } from './favourite.service';

describe('FavouriteService', () => {
let service: FavouriteService;
let httpMock: HttpTestingController;

beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [FavouriteService]
});

service = TestBed.inject(FavouriteService);
httpMock = TestBed.inject(HttpTestingController);
});

afterEach(() => {
httpMock.verify(); // Ensure that there are no outstanding requests
});

it('should be created', () => {
expect(service).toBeTruthy();
});

it('should retrieve favourites from API via GET', () => {
const dummyFavourites: Favourite[] = [{}, {}, {}];

service.getFavourites().subscribe(favourites => {
expect(favourites.length).toBe(3);
expect(favourites).toEqual(dummyFavourites);
});

const request = httpMock.expectOne(`/api/user/favourite`);
expect(request.request.method).toBe('GET');
request.flush(dummyFavourites);
});
});
3 changes: 2 additions & 1 deletion libs/ngx-kobalte/tsconfig.spec.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"src/**/*.spec.js",
"src/**/*.test.jsx",
"src/**/*.spec.jsx",
"src/**/*.d.ts"
"src/**/*.d.ts",
"src/lib/components/list-box.s.ts"
]
}

0 comments on commit 5035bea

Please sign in to comment.