我在Nodejs中创建了一个函数:
const mmm = require('mmmagic');
const mime = require('mime-types');
const {Buffer} = require("node:buffer");
const detectBodyMime = (body,callback) => {
let buffer = isBase64(body)?Buffer.from(body,'base64'):Buffer.from(body);
const magic = new mmm.Magic(mmm.MAGIC_MIME_TYPE);
magic.detect(buffer, function(err, result) {
if (err) { return callback(err); }
if(result == 'text/plain') {
try {
let text = buffer.toString();
if (text.codePointAt(0) === 0xFEFF) { // UTF8 BOM
text = text.substring(1);
}
JSON.parse(text);
return callback(null,'application/json','json',buffer);
}catch(e){
// Do nothing keep it silence we need to just verify that content is Json
}
}
return callback(null,result,mime.extension(result),buffer);
});
}
module.exports={
detectBodyMime
}
我正在为它做一些有趣的测试:
const {detectBodyMime} = require('../../../src/common/http_utils.js');
test("detectsBase64EncodedImage",(done)=>{
const content = // Populate data
detectBodyMime(content,(err,mime,extention)=>{
expect(mime).toBe('image/jpeg');
expect(extention).toBe('jpg');
expect(err).toBe(null);
done();
});
});
但是在这里我想填充:
const content = // Populate data
使用base64编码的图像。但是如果我将base64原样放置,将使代码不可读,因为我在上面放置了更多的测试。那么我可以在哪里/如何放置要测试的图像,以便我可以在测试期间将其用作数据?
在一个单独的JS fixture文件(或json文件,甚至是数据库)。
const images = {
'detectsBase64EncodedImage': 'iVBORw0KGgoAAAANSUhEUgAAAAIAAAACAQMAAABIeJ9nAAAABlBMVEUAAP//AADF+ovTAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAADElEQVQImWNgYGAAAAAEAAGjChXjAAAAAElFTkSuQmCC',
}
function getTestImage(test_name){
if (!images[test_name]) throw Error(`No image data for test [${test_name}]`)
return images[test_name]
}
module.exports = {
getTestImage,
images,
}
注意,currentTestName
也将包括describe
的名称,但是您可以自由地用任何关键字键入images对象。
const { getTestImage } = require('./thetests.fixture.js');
test("detectsBase64EncodedImage",(done)=> {
const content = getTestImage(expect.getState().currentTestName)
detectBodyMime(content,(err,mime,extention)=>{
expect(mime).toBe('image/jpeg');
expect(extention).toBe('jpg');
expect(err).toBe(null);
done();
});
});