Mocha запускает тестовый сценарий быстрее, чем ожидалось - PullRequest
0 голосов
/ 08 мая 2020

Я пытаюсь смоделировать задержку API и протестировать поведение приложения, используя mocha и nock. Хотя таймаут HTTP-клиента составляет 7 секунд, а задержка ответа составляет 10 секунд, мой тест успешно завершился через 5-10 миллисекунд, покрывая все ожидания. Вы можете увидеть пример теста ниже:

const nock = require('nock');
const axios = require('axios');
const should = require('should')

describe('test axios timeout beaviour', function () {
    const baseUrl = 'http://example.com';
    const endpoint = '/endpoint';
    nock(baseUrl).post(endpoint).delay(10 * 1000).reply(200)
    const client = axios.create({baseURL: baseUrl, timeout: 7 * 1000})

    it('should throw a timeout error', async function () {
        const startedAt = (new Date()).getTime()

        try {
            const response = await client.post(endpoint);
        } catch(e) {
            should(e).be.a.instanceOf(Error)
            should(e.message).eql('timeout of 7000ms exceeded')
            console.log((new Date()).getTime() - startedAt)
        }
    })
})

Я попытался запустить тот же тест с Jest, но это заняло 7 секунд, как и должно быть.

Это результат работы мокко и шутка:


> timeout-test@1.0.0 test /home/ibrahimgunduz/projects/personal/timeout-test
> mocha timeout.test.js && jest --testTimeout=10000 timeout.test.js

// From Mocha

  test axios timeout beaviour
**6 ms**
    ✓ should throw a timeout error


  1 passing (12ms)


// From JEST  

 PASS  ./timeout.test.js (7.367 s)
  test axios timeout beaviour
    ✓ should throw a timeout error (7053 ms)

  console.log
    **7025 ms**

      at Object.<anonymous> (timeout.test.js:20:12)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        7.843 s, estimated 8 s
Ran all test suites matching /timeout.test.js/i.
Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.

Почему время выполнения отличается, хотя код тот же?

...