mercredi 28 octobre 2020

How to verify the coverage of Microservice contract tests

I have few grpc based microservices. I used the .proto file and created some contract tests for my microservice. Is there any method or tool that I can use to verify the contract test coverage?

React Native test function inside functional component using Jest

I have the following React Native functional component that has a function getNum() that I would like to test:

export default () => {
  function getNum(num) {
    return num;
  }
};

I have tried writing the following test:

it('test', () => {
  const test = renderer.create(<Test />).getInstance();
  expect(test.getNum(2)).toBe(2);
});

I get the following error:

TypeError: Cannot read property 'getNum' of null

Am I missing something?

Testing BehaviorSubject as Observable in Angular - Jasmine

I am very newbie with testing and I am having troubles to test the following code:

ngOnInit() {
    ... some piece of code
    this.dataService.currentUserDataObservable.pipe(
      takeUntil(this.ngUnsubscribe)
    ).subscribe(
      currentUserData => {
        this.currentUser = currentUserData;
      }
    );
}

The variable this.currentUser will be used to show a button based on its properties. The variable currentUserDataObservable is a BehaviorSubject.asObservable(). When the user do the login the currentUserDataSubject inside dataService will call its next function to send the currentUserData.

I want to write a test to check if the button is being showed when the properties are true (something like this.currentUser.showButton == true) and another test to check otherwise.

What is the proper way to do that. I read some articles talking about spyOn, fakeAsync, but I could not reproduce for this specific case.

Thank you

Need to write a unit test for service on Jest

Help me fix the error, and if possible improve the test itself, because it will be based on further tests for services.

I hope for your help

This is my service file

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { createQueryBuilder, getConnection, getRepository, Repository, getManager, Connection } from 'typeorm';
import { Brands } from './brands/brands.entity';
import { Categories } from './categories/categories.entity';
import { Volumes } from './volumes/volumes.entity';
import { Packages } from './packages/packages.entity';
import { Tags } from './tags/tags.entity';
import { Countries } from './countries/countries.entity';
import { Sub_categories } from './sub_categories/sub_categories.entity';
import { Products } from './products.entity';

import { IProduct } from './products.interface';
import { Collections } from './collections/collections.entity';

@Injectable()
export class ProductsService {

  constructor(
    @InjectRepository(Products)
    private productRepository: Repository<Products>,
  ) {}

  private readonly products: IProduct[] = [];

    

  async findAllProductsByCategory(category: string): Promise<IProduct[]> {
    const qb = getRepository(Products).createQueryBuilder("products");
    const subQuery: string = qb.subQuery()
      .select('categories.id', 'cat_id')
      .from(Categories, 'categories')
      .where(`cat_id = '${ category }'`)
    .getQuery()

    return await this.findAllProductsByArgument( 'category_id', subQuery );
  }

  async findAllProductsByArgument(argumentId1: string, subQuery1: string, argumentId2?: string, subQuery2?: string): Promise<IProduct[]> {
    const qb = getRepository(Products).createQueryBuilder("products");
    qb
    .select(
      `*, 
      Products.brand_id AS brand_id`
    )
      .addSelect('brands.brand_name', 'brand_name')
      .addSelect('brands.brand_id', 'brand_nameid')
      .addSelect('categories.cat_name', 'cat_name')
      .addSelect('categories.cat_id', 'cat_id')
      .addSelect('volumes.volume_name', 'volume_name')
      .addSelect('volumes.volume_id', 'volume_id')
      .addSelect('tags.name', 'tag_name')
      .addSelect('tags.tag_id', 'tag_nameId')
      .addSelect('sub_categories.subcat_name', 'subcategory_name')
      .addSelect('sub_categories.subcat_id', 'subcategory_id')
      .addSelect('packages.package_name', 'package_name')
      .addSelect('packages.package_id', 'package_nameId')
      .addSelect('countries.country_name', 'country_name')
      .addSelect('countries.country_id', 'country_nameId')
      .addSelect('Products.price', 'price_by_one')
      .innerJoin(Brands, 'brands', 'Products.brand_id = brands.id')
      .innerJoin(Categories, 'categories', 'Products.category_id = categories.id')
      .innerJoin(Volumes, 'volumes', 'Products.volume_id = volumes.id')
      .innerJoin(Tags, 'tags', 'Products.tag_id = tags.id')
      .innerJoin(Sub_categories, 'sub_categories', 'Products.sub_category_id = sub_categories.id')
      .innerJoin(Packages, 'packages', 'Products.package_id = packages.id')
      .innerJoin(Countries, 'countries', 'Products.country_id = countries.id')
      .where('Products.stock > Products.pack_quantity AND isshow = true')
      .andWhere(`Products.${ argumentId1 } = ${ subQuery1 }`);
  
    if(argumentId2 && subQuery2){
      qb.andWhere(`Products.${ argumentId2 } = ${ subQuery2 }`)
    }
  
    return qb.getRawMany();
  }
 }

I don't really understand how to mocking data and simulate functions

import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

import { Products } from './products.entity';
import { ProductsService } from './products.service';


class ProductsFake {
  public async find(): Promise<void> {}
}


describe('ProductsService', () => {

  let service: ProductsService;
  let repo: Repository<Products>;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        ProductsService,
        {
          provide: getRepositoryToken(Products),
          useClass: ProductsFake
        }
      ]
    }).compile();

    service = module.get(ProductsService);
    repo = module.get(getRepositoryToken(Products));
  });

  describe('finding a products', () => {

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

    it('return the products list', async () => {

      const product = new Products();
      const mockData = {
        id: 10,
        brand_name: "Brewdog",
        brand_nameid: "brewdog",
        cat_id: "pivo"
      };
      Object.assign(product, mockData);

      const productsRepositoryFindAll = jest
            .spyOn(repo, 'find')
            .mockResolvedValue([product]);

      const result = await service.findAllProductsByCategory( 'pivo' );
      expect(result[0]).toBe(product);
      expect(productsRepositoryFindAll).toBeCalled()
    });

  });

});

This is an error that appears when trying to test

йййййййййййййййййййййййййййййййййййййййййййййййййййййййййййййййййййййййййййййййй

Stubbing void method using mockito is not working

doThrow(new Exception()).when(service.method(anyString(), anyBoolean(), anyString()));

Does not working because the method returns void.

doThrow(new Exception()).when(service).method(anyString(), anyBoolean(), anyString());

Does not stub properly.

The stubbing is: method("", false, "") instead of createConsent(<any string>, <any bool>, <any string>) and I get a stubbing mismatch

 - this invocation of 'method' method:
    service.method(
    "ad6b9045-e120-44ed-94df-c8262f19409d",
    false,
    "j39fj230jf390j09jf390"
);
    -> at ....java:108)
 - has following stubbing(s) with different arguments:
    1. service.method("", false, "");

What is going on?

Add dynamic variable does not work with PostMan

I'm trying to variable incremented automatically with POSTMan

the collection details :

Body :
{
  "userName": "test",
  "text": "I've inquery please ",
  "receiverID": 0,
  "receiverUserName": "",
 
  "creatorUserId": 29,
 
  "id": 0
} 

Pre-request Script :

var value = pm.environment.get("param");

if( !value) {
    pm.environment.set("param", 1);
}

Test

pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
    
});

var value = pm.environment.get("param");

pm.environment.set("param", value.param + 1);

and here is the runner screen shoot enter image description here

Calling undefined parameter - Jest tesing

I had a problem with testing in jest and i've found solution like this:

test('the data is peanut butter', (done) => {
  function callback(data) {
    expect(data).toBe('peanut butter');
   done();
  }

  fetchData(callback);
})

It's working but... In documentation is written that jest will wait until done callback is called before finishing the test.

Could you explain why it's working like this?