Merge pull request 'Fixed problems with reading 'undefined's [Closes #11]' (#13) from fix/test-fails-undef into develop

Reviewed-on: http://85.143.176.51:3000/free-land/backend/pulls/13
This commit is contained in:
moeidtopcoder 2022-10-07 12:16:07 +00:00
commit e8675e61b0
5 changed files with 30 additions and 85 deletions

View File

@ -1,4 +1,4 @@
import { Controller, Get, HttpCode, Param, ParseUUIDPipe, Query, Req, UseFilters, UseInterceptors } from "@nestjs/common"; import { Controller, Get, HttpCode, Param, ParseUUIDPipe, Query, UseFilters, UseInterceptors } from "@nestjs/common";
import { SearchService } from "../../core/services/common/search.service"; import { SearchService } from "../../core/services/common/search.service";
import { PageInterceptor } from "../../core/interceptors/page.interceptor"; import { PageInterceptor } from "../../core/interceptors/page.interceptor";
import { ApiExtraModels, ApiGatewayTimeoutResponse, ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger"; import { ApiExtraModels, ApiGatewayTimeoutResponse, ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";

View File

@ -19,6 +19,8 @@ export enum Order {
* @returns Appropriate enum-member * @returns Appropriate enum-member
*/ */
export function toOrder(str: string): Order { export function toOrder(str: string): Order {
if (!str) return Order.DESC;
switch (str) { switch (str) {
case 'asc': return Order.ASC; case 'asc': return Order.ASC;
case 'desc': return Order.DESC; case 'desc': return Order.DESC;

View File

@ -1,5 +1,5 @@
import { HttpService } from "@nestjs/axios"; import { HttpService } from "@nestjs/axios";
import { CACHE_MANAGER, CallHandler, ExecutionContext, Inject, Injectable, NestInterceptor } from "@nestjs/common"; import { BadRequestException, CACHE_MANAGER, CallHandler, ExecutionContext, Inject, Injectable, InternalServerErrorException, NestInterceptor } from "@nestjs/common";
import { Observable, map, take, switchMap, of } from "rxjs"; import { Observable, map, take, switchMap, of } from "rxjs";
import { PageDto } from "../domain/dtos"; import { PageDto } from "../domain/dtos";
import { EsTime } from "../domain/enums/es-time.enum"; import { EsTime } from "../domain/enums/es-time.enum";
@ -63,7 +63,7 @@ export class PageInterceptor implements NestInterceptor {
}; };
// Check if the performed search is a backwards search // Check if the performed search is a backwards search
let data = res.hits.hits; let data = res?.hits?.hits;
// Omitting the redundant info and leaving only the document // Omitting the redundant info and leaving only the document
data = data.map((el) => el._source); data = data.map((el) => el._source);
// Change the order if set // Change the order if set

View File

@ -1,5 +1,5 @@
import { HttpService } from "@nestjs/axios"; import { HttpService } from "@nestjs/axios";
import { GatewayTimeoutException, Injectable, NotFoundException } from "@nestjs/common"; import { GatewayTimeoutException, ImATeapotException, Injectable, NotFoundException } from "@nestjs/common";
import { map, take } from "rxjs"; import { map, take } from "rxjs";
import { EsResponseDto, SearchQueryDto} from "../../domain/dtos"; import { EsResponseDto, SearchQueryDto} from "../../domain/dtos";
import { EsQueryDto } from "../../domain/dtos/elastic/es-query.dto"; import { EsQueryDto } from "../../domain/dtos/elastic/es-query.dto";
@ -28,7 +28,7 @@ export class SearchService {
/** /**
* Finds a paper by its own ID * Finds a paper by its own ID
* @param uuid * @param uuid String, that represents unique identifier of a paper
* @returns Elasticsearch hits or an error object * @returns Elasticsearch hits or an error object
*/ */
async findByID(uuid: string): Promise<EsResponseDto> { // Should I change 'object' to specific DTO? async findByID(uuid: string): Promise<EsResponseDto> { // Should I change 'object' to specific DTO?
@ -48,12 +48,12 @@ export class SearchService {
})) }))
?.pipe(take(1), map(axiosRes => axiosRes.data)) ?.pipe(take(1), map(axiosRes => axiosRes.data))
.subscribe((res: EsResponseDto) => { .subscribe((res: EsResponseDto) => {
if (!res.hits.hits.length) {
reject(new NotFoundException);
}
if (res.timed_out) { if (res.timed_out) {
reject(new GatewayTimeoutException('Elasticsearch Timed Out')); reject(new GatewayTimeoutException('Elasticsearch Timed Out'));
} }
if (!res?.hits?.hits?.length) {
reject(new NotFoundException);
}
resolve(res); resolve(res);
}); });
} catch (error) { } catch (error) {
@ -65,7 +65,7 @@ export class SearchService {
/** /**
* Finds relevant documents by context using the given query string * Finds relevant documents by context using the given query string
* @param query, <EsQueryDto> * @param query, <EsQueryDto>
* @returns Elasticsearch hits or an error object * @returns Elasticsearch response
*/ */
async findByContext(query: SearchQueryDto): Promise<EsResponseDto> { async findByContext(query: SearchQueryDto): Promise<EsResponseDto> {
// Contruct a body for querying Elasticsearch // Contruct a body for querying Elasticsearch
@ -86,7 +86,7 @@ export class SearchService {
headers: {'Content-Type': 'application/json'}, headers: {'Content-Type': 'application/json'},
})) }))
?.pipe(take(1), map(axiosRes => axiosRes.data)) ?.pipe(take(1), map(axiosRes => axiosRes.data))
.subscribe((res: EsResponseDto) => { ?.subscribe((res: EsResponseDto) => {
if (res.timed_out) { if (res.timed_out) {
reject(new GatewayTimeoutException('Elasticsearch Timed Out')); reject(new GatewayTimeoutException('Elasticsearch Timed Out'));
} }

View File

@ -3,7 +3,7 @@ import { GatewayTimeoutException, HttpException } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config"; import { ConfigModule } from "@nestjs/config";
import { Test } from "@nestjs/testing"; import { Test } from "@nestjs/testing";
import { of } from "rxjs"; import { of } from "rxjs";
import { EsQueryDto, EsResponseDto } from "src/core/domain"; import { SearchQueryDto } from "src/core/domain";
import { SearchService } from "src/core/services/common/search.service"; import { SearchService } from "src/core/services/common/search.service";
describe('Unit tests for SearchService', () => { describe('Unit tests for SearchService', () => {
@ -42,26 +42,6 @@ describe('Unit tests for SearchService', () => {
expect(httpGetSpy).toHaveBeenCalled(); expect(httpGetSpy).toHaveBeenCalled();
}); });
// it('Should send correct data via HttpService.get() body parameter', () => {
// let httpGetSpy = jest.spyOn(httpService, 'get');
// const uuid = 'thisIsUUID_Provided';
// searchService.findByID(uuid);
// expect(httpGetSpy).toHaveBeenCalledWith<[string, object]>(expect.anything(), {
// data: {
// size: 1,
// query: {
// query_string: {
// query: 'id:' + uuid
// }
// },
// search_after: undefined,
// sort: undefined,
// },
// headers: { 'Content-Type': 'application/json' }
// });
// });
it('Should call HttpService.get() with correct URI and port number', () => { it('Should call HttpService.get() with correct URI and port number', () => {
let httpGetSpy = jest.spyOn(httpService, 'get'); let httpGetSpy = jest.spyOn(httpService, 'get');
@ -76,28 +56,6 @@ describe('Unit tests for SearchService', () => {
expect(searchService.findByID('')).toBeInstanceOf(Promise); expect(searchService.findByID('')).toBeInstanceOf(Promise);
}); });
// it('Should return a Promise with EsResponseDto', () => {
// // Axios response mock
// httpService.get = jest.fn().mockReturnValueOnce(
// of({
// status: undefined,
// statusText: undefined,
// headers: undefined,
// config: undefined,
// data: {
// took: 1,
// timed_out: false,
// hits: {
// total: {},
// hits: [{}]
// }
// },
// })
// );
// expect(searchService.findByID('')).resolves.toBeInstanceOf(EsResponseDto)
// });
// Errors // Errors
it('Should throw 504 | GatewayTimeoutException', () => { it('Should throw 504 | GatewayTimeoutException', () => {
// Axios response mock // Axios response mock
@ -136,25 +94,27 @@ describe('Unit tests for SearchService', () => {
it('Should touch HttpService.get() method', () => { it('Should touch HttpService.get() method', () => {
let httpGetSpy = jest.spyOn(httpService, 'get'); let httpGetSpy = jest.spyOn(httpService, 'get');
searchService.findByContext(null); searchService.findByContext({query: ""});
expect(httpGetSpy).toHaveBeenCalled(); expect(httpGetSpy).toHaveBeenCalled();
}); });
it('Should send correct data via HttpService.get() body parameter', () => { it('Should send correct data via HttpService.get() body parameter', () => {
let httpGetSpy = jest.spyOn(httpService, 'get'); let httpGetSpy = jest.spyOn(httpService, 'get');
let es_query = new EsQueryDto(); const query = new SearchQueryDto('keyword', 1, 32, 'desc');
es_query = {
query: {
query_string: {
query: 'thisIsTheQuery!'
}
}
}
// searchService.findByContext(es_query); searchService.findByContext(query);
expect(httpGetSpy).toHaveBeenCalledWith<[string, object]>(expect.anything(), { expect(httpGetSpy).toHaveBeenCalledWith<[string, object]>(expect.anything(), {
data: es_query, data: {
query: {
query_string: {
query: 'keyword',
default_field: 'content',
}
},
from: 32,
size: 1,
},
headers: { 'Content-Type': 'application/json' } headers: { 'Content-Type': 'application/json' }
}); });
}); });
@ -162,7 +122,7 @@ describe('Unit tests for SearchService', () => {
it('Should call HttpService.get() with correct URI and port number', () => { it('Should call HttpService.get() with correct URI and port number', () => {
let httpGetSpy = jest.spyOn(httpService, 'get'); let httpGetSpy = jest.spyOn(httpService, 'get');
searchService.findByContext(null); searchService.findByContext({query: ""});
expect(httpGetSpy).toHaveBeenCalledWith<[string, object]>( expect(httpGetSpy).toHaveBeenCalledWith<[string, object]>(
`http://${process.env.ES_CONTAINER_NAME}:${process.env.ES_PORT}/_search`, `http://${process.env.ES_CONTAINER_NAME}:${process.env.ES_PORT}/_search`,
expect.anything() expect.anything()
@ -170,26 +130,9 @@ describe('Unit tests for SearchService', () => {
}); });
it('Should return a Promise', () => { it('Should return a Promise', () => {
expect(searchService.findByContext(null)).toBeInstanceOf(Promise); expect(searchService.findByContext({query: ""})).toBeInstanceOf(Promise);
}); });
// it('Should return a Promise with EsResponseDto', () => {
// // Axios response mock
// httpService.get = jest.fn().mockReturnValueOnce(
// of({
// status: undefined,
// statusText: undefined,
// headers: undefined,
// config: undefined,
// data: {
// dummy: 'dum'
// }
// })
// );
// expect(searchService.findByContext(null)).resolves.toMatchObject<EsResponseDto>(null);
// });
// Errors // Errors
it('Should throw 504 | GatewayTimeoutException', () => { it('Should throw 504 | GatewayTimeoutException', () => {
// Axios response mock // Axios response mock
@ -206,7 +149,7 @@ describe('Unit tests for SearchService', () => {
}) })
); );
searchService.findByContext(null).catch((err) => { searchService.findByContext({query: ""}).catch((err) => {
expect(err).toBeInstanceOf(GatewayTimeoutException); expect(err).toBeInstanceOf(GatewayTimeoutException);
}); });
}); });
@ -216,7 +159,7 @@ describe('Unit tests for SearchService', () => {
throw new HttpException({ oops: 'sorry' }, 999); throw new HttpException({ oops: 'sorry' }, 999);
}); });
searchService.findByContext(null).catch((err) => { searchService.findByContext({query: ""}).catch((err) => {
expect(err).toBeInstanceOf(HttpException); expect(err).toBeInstanceOf(HttpException);
expect(err.response).toEqual({ oops: 'sorry' }); expect(err.response).toEqual({ oops: 'sorry' });
expect(err.status).toEqual(999); expect(err.status).toEqual(999);