google – I cannot conquer code coverage inside Promise “then” and “catch”

I am trying to gain code coverage on my component by implementing a unit test in my spec file, as follows:

home.component.spec.ts

import { HomeService } from './home.service';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';

import { HomeComponent } from './home.component';
import { of } from 'rxjs';

describe('HomeComponent', () => {
  let component: HomeComponent;
  let fixture: ComponentFixture<HomeComponent>;

  // stubs
  const registryStub: HomeComponent = jasmine.createSpyObj('HomeComponent', ('getUserData'));
  const fakeNames = {x: 1};

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: (HttpClientTestingModule),
      declarations: (HomeComponent)
    })
      .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(HomeComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });


  it('should navigate on promise - success', fakeAsync(() => {

    spyOn(component, 'getUserData').and.returnValue(of(fakeNames));
    (registryStub.getUserData as jasmine.Spy).and.returnValue(Promise.resolve(('test')));
    component.getUserData();

    tick();
    expect(component.getUserData).toHaveBeenCalled();



    // spyOn(component, 'getUserData').and.returnValue(of(fakeNames));
    // component.getUserData().toPromise()
    // .then((data: any) => {
    //   expect(data).toEqual(fakeNames);
    // });




  }));


});

When I run the “ng test –code-coverage” command, I check that the code gap inside the “then” and “catch” blocks are not being covered, as you might see in the illustration below:
code coverage is not being conquered within the red colored area

Could anyone point me to the right direction in order to have a complete code coverage on this component?

By the way, I have a public repo for this:

I look forward to having a reply from you guys

Thanks in advance folks!

postgresql – Can I assume that all database return a promise?

I am designing a set of unit and integration tests with a friend of mine, and we had a doubt. We know the answer, at least, more like to be true. However, we would like to hear your thoughts.

We are designing a test to MongoDB, and we expect that we receive a promise, after asking to save a document. So far so good.

What about if we change the database??? can we assume for sure that all databases when queried will return a promise??

I guess regarding the _id, it depends from database to database, we are using _id from MongoDB for testing reasons.

We are using the following test using in Jest

            create://this method do exist on service, however, at the moment of testing, it is empty, just a placeholder
              jest.fn().mockImplementation((cat: CreateCatDto) =>
                Promise.resolve({ _id: 'a uuid', ...cat })
              )

The idea is to design backends that do not depend on the database, but for testing and developing reasons, we are using MongoDB and postgresql.

Thanks in advance,

Jorge and Carol

javascript – how to get value from promise?

I saved data into AsyncStorage in reactnative project.
then I want to read data from that and filter perioddata with first cell after split.

//save data:
  const storeSelectedfarm = async (value) => {//value is "2:1"
    try {
      await AsyncStorage.setItem("mydata", value);
    } catch (e) {
      // saving error
    }
  };


//my data
let perioddata = (
    { key: "43", masterref: "1", name: "period12" },
    { key: "44", masterref: "1", name: "period13" },
    { key: "45", masterref: "2", name: "period20" },
    { key: "46", masterref: "1", name: "period14" });


//my get data code
{perioddata.filter(function (item) {
                let saveddata = async () =>
                  await AsyncStorage.getItem("mydata")
                    .then(function (result) {
                      return result;
                    })
                    .catch(function (err) {
                      return "2:1";
                    });
                return (
                  item.masterref=== saveddata.split(":")(0).trim()
                );
              })}

error: saveddata.split is not a function. (In ‘saveddata.split(“:”)’, ‘saveddata.split’ is undefined)

async – Como converter uma função baseada em promise para callback em JavaScript?

Podemos converter funções assíncronas que trabalham com callback para trabalharem com promises, como demonstrado nos exemplos abaixo:

callback:

const timeInMs = 1_000;

function asyncCallback(timeMs, callback) {
  setTimeout(() => callback(null, timeMs), timeMs);
}

console.log('first');

asyncCallback(timeInMs, (err, result) => {
  if (err) return console.log('Error: ', err);

  console.log('last');

  console.log('Time passed: ', result);
});

console.log('second');

Mudando para promise:

const timeInMs = 1_000;

function asyncCallback(timeMs, callback) {
  setTimeout(() => callback(null, timeMs), timeMs);
}

// função simples para converter callback em promise
function promisify(callback) {
  return function promisified(...args) {
    return new Promise((resolve, reject) => {
      const argsArray = (
        ...args,
        function (err, result) {
          if (err) return reject(err);

          resolve(result);
        },
      );

      callback(...argsArray);
    });
  };
}

// promisificando e convertendo a função asyncCallback
const asyncPromise = promisify(asyncCallback);

console.log('first');

asyncPromise(timeInMs).then((result) => {
  console.log('last');

  console.log('Time passed: ', result);
});

console.log('second');

// usando async/await
(async () => {
  const result = await asyncPromise(timeInMs);

  console.log('(async/await) Time passed: ', result);
})();

Repare que foi possível mudar de callback para promise graças a função customizada promisify().

A pergunta é:

  • Como converter uma função baseada em promise para callback, ou seja, fazer o oposto de promisify()? Algo como callbackify().

Tem uma função no Node.js chamada callbackify do core module util que faz já faz o caminho inverso:

import { callbackify } from 'util'

const timeInMs = 1_000

function asyncCallback (timeMs, callback) {
  setTimeout(() => callback(null, timeMs), timeMs)
}

function promisify (callback) {
  return function promisified (...args) {
    return new Promise((resolve, reject) => {
      const argsArray = (
        ...args,
        function (err, result) {
          if (err) return reject(err)

          resolve(result)
        },
      )

      callback(...argsArray)
    })
  }
}

const asyncPromise = promisify(asyncCallback)

const callbackFunction = callbackify(asyncPromise)

callbackFunction(timeInMs, (err, result) => {
  console.log('Time passed: ', result) // Time passed:  1000
})

Mas eu quero saber como seria feito uma função “na mão” (semelhante à promisify()), com passo a passo e com explicação detalhada, porque quero entender a lógica de implementação.

Esta minha dúivida é só uma prova de conceito e gostaria de saber…

Typescript : Adding types to a function that takes in a string and returns a different promise based on the string

The problem here is that the interface IAnimal is not what those apis return. You want to return that interface from your function, but those APIs should have their own interface representing the response data.

interface DogApiResponse {
  message: string
  status: string
}

interface FoxApiResponse {
  image: string
}

interface Animal {
  status: string
  image: string | null
}

To generalize the set of available animal types I propose to also add interface for the fetching part of individual APIs.

declare type RandomAnimalFactory = () => Promise<Animal>

Now we declare two factories – for dogs and foxes

const dogFactory: RandomAnimalFactory = async () => {
  const result: DogApiResponse = await fetch(dogApiUrl).then(data => data.json())
  if (result.status !== 'success') {
    throw new Error('Dog API railure')
  }
  return {image: result.message, status: 'success'}
}

const foxFactory: RandomAnimalFactory = async () => {
  const result: FoxApiResponse = await fetch(foxApiUrl).then(data => data.json())
  return {image: result.image, status: 'success'}
}

The we can have the named animal factory work like this

declare type NamedAnimalFactory = (name: string) => Promise<Animal>


const createRandomNamedAnimalFactory = (randomFactories: {(key: string): RandomAnimalFactory}): NamedAnimalFactory => {
  return async (name) => {
    const factory = randomFactories(name.trim().toLowerCase())
    if (!factory) {
      return {image: null, status: 'failure'}
    }

    try {
      return await factory()
    } catch {
      return {image: null, status: 'failure'}
    }
  }
}

const getAnimal: NamedAnimalFactory = createRandomNamedAnimalFactory({
  dog: dogFactory,
  fox: foxFactory,
})
```

javascript – JS Promise com .then() customizado

Gostaria de saber se o que estou fazendo está na maneira correta
O que quero fazer é criar uma Promise com um “.then()” customizado
ex: myPromise.accepted(value => console.log(value))

o que eu consegui fazer

Promise.prototype.accepted = Promise.prototype.then

const myPromise = new Promise((resolve, reject) => {
    resolve(true)
})

myPromise.accepted(status => console.log(status))

mas não sei se é a maneira correta de se fazer

reactjs – Unhandled Promise Rejection in the ABP React Mobile Framework

I am running the ABP React Mobile code from https://abp.io/

Steps to replicate from scratch:

  1. Create an ABP project
  2. Migrate the DB
  3. Log in to web app
  4. Create user and log in to test if DB will update
  5. Set up Conveyor to get IP address for react front end
  6. Ran Yarn to init react project
  7. Opened react project and added IP and port from Conveyor to Environment.js
  8. Ran Yarn start
  9. Open Expo on iOS and open project
  10. Log in with Admin and User credentials

Results in this error:

(Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'delete state.activeLoadings(action.payload.key)'))
* srcstorereducersLoadingReducer.js:10:6 in builder.addCase$argument_1
* http://10.0.0.192:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:211765:15 in <unknown>
* (native code):null in <unknown>
* (native code):null in reduce
- node_modulesreduxlibredux.js:463:34 in combination
* http://10.0.0.192:19001/node_modules%5Cexpo%5CAppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:228985:32 in <unknown>
- node_modulesreduxlibredux.js:217:8 in dispatch
- node_modules@redux-sagacoredistredux-saga-core.dev.cjs.js:1412:9 in <anonymous> 
* srcscreensLoginLoginScreen.js:52:8 in login.then.then$argument_0
- node_modulesreact-nativenode_modulespromisesetimmediatefinally.js:12:28 in then$argument_1
- node_modulesreact-nativenode_modulespromisesetimmediatecore.js:37:13 in tryCallOne
- node_modulesreact-nativenode_modulespromisesetimmediatecore.js:123:24 in setImmediate$argument_0
- node_modulesreact-nativeLibrariesCoreTimersJSTimers.js:130:14 in _callTimer    
- node_modulesreact-nativeLibrariesCoreTimersJSTimers.js:181:14 in _callImmediatesPass
- node_modulesreact-nativeLibrariesCoreTimersJSTimers.js:441:30 in callImmediates- node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:387:6 in __callImmediates
- node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:135:6 in __guard$argument_0
- node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:364:10 in __guard 
- node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:134:4 in flushedQueue
* (native code):null in flushedQueue
* (native code):null in callFunctionReturnFlushedQueue

Code related to error:

import { createReducer } from '@reduxjs/toolkit';
import LoadingActions from '../actions/LoadingActions';

const initialState = { activeLoadings: {}, loading: false };

export default createReducer(initialState, builder =>
  builder
    .addCase(LoadingActions.start, (state, action) => {
      const { key, opacity } = action.payload;
      return {
        ...state,
        actives: { ...state.activeLoadings, (key): action },
        loading: true,
        opacity,
      };
    })
    .addCase(LoadingActions.stop, (state, action) => {
      delete state.activeLoadings(action.payload.key);

      state.loading = !!Object.keys(state.activeLoadings).length;
    })
    .addCase(LoadingActions.clear, () => ({})),
);

javascript – Promise {} al tratar de retornar el valor de una promesa

Tu problema es que las peticiones a APIs son asíncronas, es decir, cuando realizas una petición, el código puede seguir avanzando sin haber obtenido la respuesta de la misma (te la puede dar durante la petición, al final de la petición o nunca).

En tu caso, es lo que está pasando, te está retornando una promesa.

Tu problema tiene una solución fácil:

const APIRequest = async () => {
    const respuesta  = await axios.get(`http://localhost:3000/parts/part/${this.codigo}`)
    await respuesta.then((response) => {return response.data.exists}); 
} // Como sólo pones un trozo de código, te he encapsulado todo en una función para añadir async al método.
if (respuesta) {
//logica } 
else {
//logica
}

Como puedes ver, el código está exactamente igual, pero con dos palabras claves dentro.

  1. Async: Avisa al compilador que la función es asíncrona (por cada tick de reloj del procesor no tiene porqué ejecutar una instrucción).
  2. Await: Debe estar acompañada por async, toda función o variable que tenga esta palabra clave, no seguirá ejecutando código hasta que se haya obtenido la respuesta.

Con estas dos soluciones, tu código ya debería ser funcional.

Pero, en el caso de que no funcionara, te recomiendo realizar el siguiente cambio:

const APIRequest = async () => {
    const respuesta  = axios.get(`http://localhost:3000/parts/part/${this.codigo}`)
    respuesta.then((response) => {
        let respuesta = response.data.exists;
        if (respuesta) {
          //logica 
        } else {
          //logica
        }
    });
}

Es decir, mover el if/else dentro del .then de la petición a la api.

sharepoint online – Promise is missing properties

When I try to create array, to put the results in the array, then I get the following error message:

const allItems : any () = sp.web.lists.getByTitle("Documents").items.get();

Type ‘Promise<any()>’ is missing the following properties from type
‘any()’: length, pop, push, concat, and 16 more.ts(2740)

What am I doing wrong?

node.js – NodeJS promise loop through all files in directory

I am trying to re-organise my mp3 collection based on its id3 meta data into folders based on the artist. I’m new to nodeJs and more importantly promises. I was hoping I could get some feedback on my script. I can manage the creating of folders and copying of files quite easily, but I’m a little unsure on the async reading and looping part (shown below).

It does run, but almost crashes my computer when I run it on the full directory.

Thanks in advance for any suggestions or advice.

const fs = require('fs');
const NodeID3 = require('node-id3-promise')
const util = require("util");

const testFolder = '/home/james/Music';
const reorderedFolder = '/home/james/Music/reordered';

const existsProm = util.promisify(fs.access);
const statsProm = util.promisify(fs.stat);
const mkdirProm = util.promisify(fs.mkdir);
const copyFileProm = util.promisify(fs.copyFile);
const removeFileProm = util.promisify(fs.rm);
const readAllFiles = util.promisify(fs.readdir);

const isDelete = false;

async function getFiles(){
    const files = await readAllFiles(testFolder);
    return Promise.all(files);
}

(async ()=>{

    const files = await getFiles();

    files.forEach(file => {
        var sourceFilePath = testFolder + "/" + file;

        Promise.resolve(sourceFilePath)
            .then(filePath =>{
                //Return an array of promises. a) does file exist, b) filePath
                return Promise.all((existsProm(filePath), Promise.resolve(filePath)));
            })
            .catch(err =>{
                //File wasn't found. Kill it.
                throw new Error("File not found");
            })
            .then(fileExistsAndFilePath => {
                //get tags for existing file path.
                return Promise.all((NodeID3.read(fileExistsAndFilePath(1)), fileExistsAndFilePath(1)))
            })
            .then(tagAndFilePath => {
                //get the id3 tag info and create an object from it.
                var tagDetails = {};
                tagDetails.artist = tagAndFilePath(0).artist;
                tagDetails.title = tagAndFilePath(0).title;
                tagDetails.filePath = tagAndFilePath(1);

                return tagDetails;
            })
            .then(tagDetails => {
                //Create file paths
                if(tagDetails != null && tagDetails.artist != null && tagDetails.title != null){
                    var fileAndFolder = {};
                    fileAndFolder.existingFilePath = tagDetails.filePath;
                    fileAndFolder.newFolderPath = reorderedFolder + "/" + tagDetails.artist;
                    fileAndFolder.newFilePath = fileAndFolder.newFolderPath + "/" + tagDetails.title + ".mp3";
                    return fileAndFolder;
                }else{
                    throw new Error("No artist");
                }
            })
            .then(fileAndFolder => {
                //Create the directory, if it exists, ignore the error
                return Promise.all((mkdirProm(fileAndFolder.newFolderPath).catch(err => {}), fileAndFolder));
            })
            .then(mdkirAndFileAndFolder => {
                //Copy the file to the new location
                return Promise.all((
                    copyFileProm(mdkirAndFileAndFolder(1).existingFilePath, mdkirAndFileAndFolder(1).newFilePath).catch(err => {
                        console.log(err);
                        throw new Error("Problem copying file");
                    }),
                    mdkirAndFileAndFolder(1)
                ));
            })
            .then(copyFileResultAndFileAndFolder => {
                //Remove the old file
                if(isDelete){
                    return Promise.all((
                        removeFileProm(copyFileResultAndFileAndFolder(1).existingFilePath).catch(err => {console.log("Problem deleting file " + err);}),
                        copyFileResultAndFileAndFolder(1).existingFilePath
                    ));
                }else{
                    return Promise.all((null, copyFileResultAndFileAndFolder(1).existingFilePath));
                }
            })
            .then(rmFileResult => {
                //Output success message
                console.log(rmFileResult(1) + " = successfully moved.");

                return true;
            })
            .catch(error => {
                if(error.message != "File not found" && error.message != "No artist"){
                    console.error(error);
                }
            })
    });
})()