【发布时间】:2018-11-21 06:16:15
【问题描述】:
我有一个异步函数,我想同时测试:成功和失败。成功时函数返回一个字符串,失败时抛出。我在测试失败方面失败得很惨。这是我的代码:
- getKmlFileName.test.js
我已通过注释失败的代码禁用并将结果添加到 cmets
'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 文档中示例的不同之处在于它们展示了如何测试函数 throws 以及如何测试 rejects 的 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.
从内联的 cmets 中可以看出,该函数正在做它应该做的事情,但是我不知道如何在 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;
【问题讨论】:
-
你是否总是返回一个 Promise(
getKmlFilename声明为异步)? -
@Narigo 是的,你可以在我的更新中看到
标签: javascript async-await jestjs