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:


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)

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

  it('should create', () => {

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

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


    // 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', })

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 – Cypress function randomly times out “promise that never resolved.”

I’m overwriting the visit command to run tests on our QA environment which requires authentication. Most of the time it works fine but sometimes it fails with

cy.then() timed out after waiting 4000ms.

Your callback function returned a promise that never resolved.

My function is:

Cypress.Commands.overwrite("visit", (originalFn, url, options) => {
  // Read the auth details from accounts.json
  cy.fixture("accounts").then((account) => {
    const username = account.auth_username;
    const password = account.auth_password;

    const authenticatedOptions = {
      auth: { username, password },
      failOnStatusCode: false,

    return originalFn(url, authenticatedOptions);

Am I doing something wrong to make it flakey?

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:


const timeInMs = 1_000;

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


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


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


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 = (
        function (err, result) {
          if (err) return reject(err);



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


asyncPromise(timeInMs).then((result) => {

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


// 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 = (
        function (err, result) {
          if (err) return reject(err)



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…

javascript – D3.js: Uncaught (in promise) TypeError: interpolator is not a function

Estoy intentando crear una escala de colores en un mapa pero me sale este error Uncaught (in promise) TypeError: interpolator is not a function
at scale (d3.js:14092)
at mapa.js:144
at i.eachLayer (leaflet.js:5)
at mapa.js:142

 function colorDomain() {
            let gridBoxIndex = gridBoxes() =>,
                gridBoxData = forecastData.t2(0).filter((_, i) => gridBoxIndex.indexOf(i) > -1);
            return d3.extent(gridBoxData);

        var colorScheme = d3.schemeSpectral;
        var interpolate = d3.interpolateSpectral;
        function colorScale(t) {
            let schemesNeedingInversion = ("Spectral", "RdBu", "RdYlBu", "RdYlGn");
            return d3.scaleSequential(d3(`interpolate${ colorScheme }`)).domain(
                schemesNeedingInversion.indexOf(colorScheme) > -1 ? (colorDomain()(1), colorDomain()(0)) : colorDomain()

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) => {

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

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

Tratar promise com typescript – Stack Overflow em Português

Eu tenho o seguinte método:

async sync({model, event, data}: {model: string, event: string, data: Category}) {
    if(model === 'category') {
      switch (event) {
        case 'created':
          await this.categoryRepo.create({
            createdAt: new Date(),
            updatedAt: new Date()

Quando faço a chamada dele:

this.sync({model, event, data});

O typescript me retorna o seguinte erro no this:

ESLint: Promises must be handled appropriately or explicitly marked as
ignored with the void

Como posso tratar isso?

[Unhandled promise rejection: TypeError: null is not an object (evaluating ‘bleManager.scan’)]

Estou com o seguinte erro na conexão bluetooth com React Native, estou utilizando a biblioteca react-native-ble-manager e o expo para a construção deste app.

O erro ocorre quando tento chamar o metodo startScan().

Busquei em alguns locais e explicaram que deveria excluir as pastas do projeto e reconstruí-las. Pois é um problema de instalação da lib react-native-ble-manager. Porém, não consigui resolver com base nestas pesquisas.

Segue código abaixo:

import BleManager from 'react-native-ble-manager';

const BleManagerModule = NativeModules.BleManager;
const bleManagerEmitter = new NativeEventEmitter(BleManagerModule);

function HomeScreen({ navigation }) {

  return (
    <View style={{ flex: 1, alignItems: 'flex-start', justifyContent: 'flex-start' }}>
      <View style={{ flex: 0.05, alignItems: 'flex-start', justifyContent: 'flex-start' }}>
        title="Open navigation drawer"

      <Button title="Buscar aparelhos" onPress={() => bt.startScan() } />

Segue código de conexão bluetooth:

export class Blue extends Component {

    this.state = {
      peripherals: new Map(),
      //appState: ''

    this.handleDiscoverPeripheral = this.handleDiscoverPeripheral.bind(this);
    this.handleStopScan = this.handleStopScan.bind(this);
    this.handleUpdateValueForCharacteristic = this.handleUpdateValueForCharacteristic.bind(this);
    this.handleDisconnectedPeripheral = this.handleDisconnectedPeripheral.bind(this);
    this.handleAppStateChange = this.handleAppStateChange.bind(this);
  componentDidMount() {
    AppState.addEventListener('change', this.handleAppStateChange);

    BleManager.start({showAlert: false});

    this.handlerDiscover = bleManagerEmitter.addListener('BleManagerDiscoverPeripheral', this.handleDiscoverPeripheral );
    this.handlerStop = bleManagerEmitter.addListener('BleManagerStopScan', this.handleStopScan );
    this.handlerDisconnect = bleManagerEmitter.addListener('BleManagerDisconnectPeripheral', this.handleDisconnectedPeripheral );
    this.handlerUpdate = bleManagerEmitter.addListener('BleManagerDidUpdateValueForCharacteristic', this.handleUpdateValueForCharacteristic );

    if (Platform.OS === 'android' && Platform.Version >= 23) {
        PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION).then((result) => {
            if (result) {
              console.log("Permission is OK");
            } else {
              PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION).then((result) => {
                if (result) {
                  console.log("User accept");
                } else {
                  console.log("User refuse");


  startScan() {

    if (!this.state.scanning) {
      //this.setState({peripherals: new Map()});
      BleManager.scan((), 3,true)
        .then((results) => {

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?