FLC*_*FLC 11 javascript async-await jestjs
我有一个异步函数,我想同时测试:成功和失败。成功时函数返回一个字符串,失败时抛出。我在测试失败方面惨遭失败。这是我的代码:
我通过评论失败的代码并在评论中添加结果来禁用
'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');
}
});
});
Run Code Online (Sandbox Code Playgroud)
如您所见,没有任何效果。我相信我的测试几乎是第一个失败测试的Promises示例和最后一个的Async/Await示例的精确副本,但是没有一个有效。
我相信与 Jest 文档中的示例的不同之处在于它们展示了如何测试函数throws 以及如何测试 Promise that rejects。但我的承诺拒绝了投掷。
检查节点控制台中的功能我得到这个日志:
// 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.
Run Code Online (Sandbox Code Playgroud)
从内联注释中可以看出,该函数正在做它应该做的事情,但是我不知道如何在 Jest 中测试它。任何帮助将不胜感激。
我觉得这里的代码看起来太复杂了,我准备了一个存储库,其中包含我学习 Jest 的不幸经历
2018.06.12 更新:
不知何故,我的消息被打乱并丢失了第一部分,这是我试图测试的实际代码,对此我深表歉意,它是:
获取Kml文件名.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;
Run Code Online (Sandbox Code Playgroud)在您的第一次测试中:
return getKmlFilename(createEmptyFolder())
.catch(e => expect(e).toMatch('No valid KML file in'));
Run Code Online (Sandbox Code Playgroud)
如果 Promise 解决,它不会抱怨。
在第二次测试中
try {
const result = await getKmlFilename(createEmptyFolder());
} catch (e) {
...
}
Run Code Online (Sandbox Code Playgroud)
如果 Promise 解决,它也不会抱怨,因为它不会进入 catch 块。
要测试 Promise,请问自己以下问题:
Error还是常规对象?开玩笑,你应该能够做到这一点:
expect(yourThing()).resolves.toMatchSnapshot()expect(yourThing()).resolves.toThrow(/something/)expect(yourThing()).rejects.toThrow(/something/)expect(yourThing()).rejects.toMatchSnapshot()请注意,异步函数始终返回一个值(一个 Promise 对象),因此“通常”expect(() => yourThing()).toThrow()将不起作用。您需要首先等待 Promise 的结果(通过使用resolves或rejects),然后对其进行测试。
| 归档时间: |
|
| 查看次数: |
15596 次 |
| 最近记录: |