我正在使用 fast-xml-parser,它试图编写一些测试用例,但在 Javascript 代码中的一些纯文本上出现故障。但是,访问该站点的在线网页以尝试验证器,返回错误。
我的 XML 检查
import * as XmlLib from 'fast-xml-parser';
class XmlWrapper {
public static IsXML(XML: string): boolean | never {
try {
const XmlParser: XmlLib.XMLParser = new XmlLib.XMLParser({ allowBooleanAttributes: true });
const _Result = XmlParser.parse(XML);
// Just using the validate directly has the same issue
// const _Result = XmlLib.XMLValidator.validate(XML, { allowBooleanAttributes: true });
}
} catch (Exception) {
console.log(Exception);
throw new Error('Bad XML');
}
return true;
}
}
我的测试用例相当简单:
import { XmlWrapper } from './xml-wrapper';
describe('XmlWrapper', () => {
it('should be defined', () => {
expect(new XmlWrapper()).toBeDefined();
});
it.each([
['undefined', undefined],
['null', null],
['empty string', ''],
['ABC', 'ABC'],
['just <?xml starting tag', '<?xml'],
])('should throw an exception when getting %s which is an invalid value.', (_Text, Value) => {
expect(() => {
XmlWrapper.IsXML(Value);
}).toThrowError('Bad XML');
});
除 ABC 字段外,所有测试均正确通过。
FAIL src/library/wrappers/xml-wrapper.spec.ts (7.492 s)
XmlWrapper
√ should throw an exception when getting undefined which is an invalid value. (7 ms)
√ should throw an exception when getting null which is an invalid value. (3 ms)
√ should throw an exception when getting empty string which is an invalid value. (3 ms)
× should throw an exception when getting ABC which is an invalid value. (4 ms)
√ should throw an exception when getting just <?xml starting tag which is an invalid value. (5 ms)
● XmlWrapper › should throw an exception when getting ABC which is an invalid value.
expect(received).toThrowError(expected)
Expected substring: "Bad XML"
Received function did not throw
但是,使用fast-xml-parser 网页,左侧只有 ABC,然后是 Validate,可以正常工作。