Async ждут Node.js кода модульного тестирования с использованием чай и мокко - PullRequest
0 голосов
/ 02 ноября 2019

Я довольно новичок в узле и экспрессе. И пытался написать тестовый код, используя мокко, чай. Вот часть исходного кода.

googleService.js:

const axios = require('./axios');

exports.hitGoogle = async (requestUrl, payload) => {
  let response = {};
  await axios.post(`${requestUrl}`, payload)
    .then((resp) => {
      response = resp;
      console.log(response);
    })
    .catch((err) => {
      console.error(err);
    });
  return response;
};

readGoogle.js

const googleService = require('./googleService');

exports.execute = async (data) => {
  console.log(`data ${JSON.stringify(data)}`);
  console.log(`Name ${data.name}`);
  console.log(`Salary ${data.salary}`);
  console.log(`Age ${data.age}`);
  const payload = { name: data.name, salary: data.salary, age: data.age };

  await googleService.hitGoogle('http://dummy.restapiexample.com/api/v1/create', payload)
    .then((response) => {
      if (response.status === 200 || response.status === 201) {
        console.log(response.status);
        return true;
      }
      return false;
    })
    .catch((err) => {
      console.log(err);
    });
  return true;
};

А вот мой файл модульного теста:

const readGoogle = require('./readGoogle');

const jmsPayload = { age: '23', name: 'test', salary: '123' };

describe('Google ', () => {
  it('POST: Google.', async () => {
     readGoogle.execute(jmsPayload).then((result) => {
     results = result;
    console.log(`Final Result : ${results.toString()}`);
  });
});

Когда я выполняю этот файл теста, публикация прошла успешно,

hitGoogle url=http://dummy.restapiexample.com/api/v1/create
hitGoogle payload=[object Object]
{ status: 200,
  statusText: 'OK',

Входные значения переданы из класса тестав readGoogle.js также читается внутри,

data {"age":"23","name":"test","salary":"123"}
Name test
Salary 123
Age 23

**But I am getting Promise as output.** 

**SO I have rendered the promised value to a normal string and getting 'true' as final output.**

Кроме того,

  • 1) Это правильный способ тестирования модуля async-await?

    2) Нужно ли нам добавлять что-либо еще в этот тестовый код, например блоки Settimeout или beforeEach или afterEach?

    3) Нужно ли использовать Sinon для шпионажа или добавления заглушки в «полезную нагрузку»в googleService.js?

Может кто-нибудь помочь или предложить мне правильный путь?

Пробовал асинхронный способ выполнения тестовых примеров один за другим в порядке, указанном ниже,

const readGoogle = require('./readGoogle');

const jmsPayload = { age: '23', name: 'test', salary: '123' };

const common = require('./common');
const chaiHttp = common.chaiHttp;
common.chai.use(chaiHttp);

describe('Google ', () => {
  common.mocha.before((done) => {
    // Wait for the server to start up
    setTimeout(() => {
      done();
    }, 1000);
  });

  it('POST: Google.', async () => {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
  });
  it('POST: Google.', async () => {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
    setTimeout(() => {
    }, 1000);
  });
  it('POST: Google.', async () => {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
  });
  it('POST: Google.', async () => {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
  });
  it('POST: Google.', async () => {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
  });
  it('POST: Google.', async () => {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
  });
  it('POST: Google.', async () => {
    const result = readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${result.toString()}`);
  });
});

Но тогда я получаю,

Ошибка: превышено время ожидания 2000 мс. Для асинхронных тестов и хуков убедитесь, что вызывается «done ()»;если вы возвращаете обещание, убедитесь, что оно разрешено

Заранее спасибо

1 Ответ

0 голосов
/ 02 ноября 2019

Вы можете использовать 2 следующих решения:

1) Обратный вызов соглашение:

describe('Google ', () => {
    it('POST: Google.', (done) => {
        readGoogle.execute(jmsPayload).then((result) => {
            results = result;
            console.log(`Final Result : ${results.toString()}`);
            done();
        }).catch((e) => {
            done();
        });
    });
});

2) асинхронное / ожидание соглашение

describe('Google ', () => {
  it('POST: Google.', async () => {
    const results = await readGoogle.execute(jmsPayload);
    console.log(`Final Result : ${results.toString()}`);
  });
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...