尝试测试异步函数时Jest测试失败

时间:2018-06-11 23:01:11

标签: javascript async-await jestjs

我有一个异步功能,我想测试两者:成功和失败。成功时,函数返回一个字符串,失败时抛出。我在测试失败时惨遭失败。这是我的代码:

  • getKmlFileName.test.js

我通过评论失败的代码并在评论中添加结果来禁用

    'use strict';

    const path = require('path');
    const fs = require('fs');

    const getKmlFilename = require('./getKmlFileName.js');

    const createGoodFolder = () => {
      const folderPath = fs.mkdtempSync('/tmp/test-getKmlFilename-');
      const fileDescriptor = fs.openSync(path.join(folderPath, 'doc.kml'), 'w');
      fs.closeSync(fileDescriptor);
      return folderPath;
    };

    const createEmptyFolder = () => fs.mkdtempSync('/tmp/test-getKmlFilename-');

    describe('/app/lib/getKmlFilename', () => {
      // Success tests
      test('Should return a KML filename', async () => {
        const result = await getKmlFilename(createGoodFolder());
        expect(result).toMatch(/\.kml$/);
      });

      // Failure tests
      test('Should throw if no KML files in folder', () => {
        // Expected one assertion to be called but received zero assertion calls.
        // expect.assertions(1);

        // expect(function).toThrow(undefined)
        // Received value must be a function, but instead "object" was found
        //return getKmlFilename(createEmptyFolder())
        // .catch(e => expect(e).toThrow());

        // expect(string)[.not].toMatch(expected)
        // string value must be a string.
        // Received:
        // object:
        // [Error: No valid KML file in /tmp/test-getKmlFilename-j2XxQ4]

        return getKmlFilename(createEmptyFolder())
          .catch(e => expect(e).toMatch('No valid KML file in'));
      });

      test('Should throw if no KML files in folder - try/catch version',
        async () => {
        // Expected one assertion to be called but received zero assertion calls.
        // expect.assertions(1);

        try {
          const result = await getKmlFilename(createEmptyFolder());
        } catch (e) {
          // Received value must be a function, but instead "object" was found
          // expect(e).toThrow();

          // expect(string)[.not].toMatch(expected)
          // string value must be a string.
          // Received:
          // object:
          // [Error: No valid KML file in /tmp/test-getKmlFilename-3JOUAX]
          expect(e).toMatch('No valid KML file in');
        }
      });

    });

如你所见,没有任何作用。我相信我的测试几乎是第一次失败测试的Promises示例和最后一次失败测试的Async/Await示例的完全副本,但是没有效果。

我认为与Jest文档中的示例的区别在于它们展示了如何测试函数throw以及如何测试reject的Promise。但是我的承诺拒绝投掷。

检查节点控制台中的功能我得到这个日志:

// import function
> getKml = require('./getKmlFileName.js')
[AsyncFunction: getKmlFilename]
// trying it with a proper folder shows we get a Promise
> getKml('/tmp/con')
Promise {
  <pending>,
  domain: 
   Domain {
     domain: null,
     _events: { error: [Function: debugDomainError] },
     _eventsCount: 1,
     _maxListeners: undefined,
     members: [] } }
// trying it with a failing folder shows it's a rejected promise which throws
> getKml('/tmp/sin')
Promise {
  <pending>,
  domain: 
   Domain {
     domain: null,
     _events: { error: [Function: debugDomainError] },
     _eventsCount: 1,
     _maxListeners: undefined,
     members: [] } }
> (node:10711) UnhandledPromiseRejectionWarning: Error: No valid KML file in /tmp/sin
    at getKmlFilename (/home/flc/soft/learning/2018.06.08,jest/getKmlFileName.js:14:11)
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:228:7)
(node:10711) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:10711) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

从内联评论中可以看出,该功能正在做它应该做的事情,但是我不知道如何在Jest中测试它。非常感谢任何帮助。

我认为这里的代码看起来太复杂了,我准备了一个repository,其中包含我学习Jest的不幸

更新2018.06.12:

不知怎的,我的消息被混乱并丢失了第一部分,这是我试图测试的实际代码,我为此道歉,这里是:

  • getKmlFileName.js

    'use strict';
    const globby = require('globby');
    const path = require('path');
    
    const getKmlFilename = async (workDir) => {
      const pattern = path.join(workDir, '**/*.kml');
      const files = await globby(pattern);
      if (files && files.length > 0) {
        // Return first KML found, if there are others (improbable), ignore them
        return path.basename(files[0]);
      } else {
        throw new Error(`No valid KML file in ${workDir}`);
      }
    };
    
    module.exports = getKmlFilename;
    

1 个答案:

答案 0 :(得分:1)

在你的第一次测试中:

return getKmlFilename(createEmptyFolder())
  .catch(e => expect(e).toMatch('No valid KML file in'));

如果Promise结算,它不会抱怨。

在第二次测试中

try {
  const result = await getKmlFilename(createEmptyFolder());
} catch (e) {
  ...
}

如果Promise解决它也不会抱怨,因为它不会进入catch块。

要测试Promises,请问自己这些问题:

  1. 承诺是否成功(解决)或失败(拒绝)?
  2. 您的结果或拒绝值是Error还是常规对象?
  3. 开玩笑,你应该能够做到这一点:

    1. 解析为常规对象:expect(yourThing()).resolves.toMatchSnapshot()
    2. 解决错误(从未见过): expect(yourThing()).resolves.toThrow(/something/)
    3. 拒绝错误: expect(yourThing()).rejects.toThrow(/something/)
    4. 拒绝常规对象(你确定要这个吗?): expect(yourThing()).rejects.toMatchSnapshot()
    5. 请注意,异步函数总是返回一个值(一个Promise对象),所以&#34;通常&#34; expect(() => yourThing()).toThrow()无效。您需要先等待Promise的结果(使用resolvesrejects),然后再进行测试。