【发布时间】:2022-02-10 07:38:25
【问题描述】:
我的nestjs中有以下文件。
import { extname } from 'path';
import { diskStorage } from 'multer';
import { v4 as uuid } from 'uuid';
import { HttpException, HttpStatus } from '@nestjs/common';
export const multerConfig = {
dest: process.env.UPLOAD_LOCATION,
};
export const multerOptions = {
limits: {
fileSize: +process.env.MAX_FILE_SIZE,
},
fileFilter: (_req: any, file: any, cb: any) => {
if (file.mimetype.match(/\/(jpg|jpeg|png|gif|pdf|msg|eml)$/)) {
cb(null, true);
} else {
cb(
new HttpException(
`Unsupported file type ${extname(file.originalname)}`,
HttpStatus.BAD_REQUEST
),
false
);
}
},
storage: diskStorage({
destination: multerConfig.dest,
filename: (_req: any, file: any, cb: any) => {
cb(null, `${uuid()}${extname(file.originalname)}`);
},
}),
};
我为它写了下面的测试用例。
import { Readable } from 'stream';
import { multerConfig, multerOptions } from './multer.config';
describe('Multer Configuration ', () => {
const mockFile: Express.Multer.File = {
filename: '',
fieldname: '',
originalname: '',
encoding: '',
mimetype: '',
size: 1,
stream: new Readable(),
destination: '',
path: '',
buffer: Buffer.from('', 'utf8'),
};
it('should define destination', () => {
expect(multerConfig).toBeDefined();
expect(multerConfig.dest).toBe(process.env.UPLOAD_LOCATION);
});
it('should define multer upload options', async () => {
expect(multerOptions).toBeDefined();
expect(multerOptions.fileFilter).toBeDefined();
expect(multerOptions.storage).toBeTruthy();
expect(multerOptions.limits).toBeTruthy();
const cb = jest.fn();
multerOptions.fileFilter({}, mockFile, cb);
expect(cb).toHaveBeenCalled();
expect(cb).toHaveBeenCalledTimes(1);
expect(cb()).toBeFalsy();
});
afterAll(() => {
jest.resetAllMocks();
});
});
两个测试用例都成功,但是当我检查代码覆盖率时,它只显示 50%。它显示行 16 和 31 未覆盖。
第 16 行是
cb(null, true); it comes inside the `if` block
第 31 行是
cb(null, `${uuid()}${extname(file.originalname)}`);
您能帮我介绍一下这部分吗?我真的很挣扎。 我需要额外的测试用例还是需要修改现有的测试用例?
编辑1:-
const fileType = 'jpg';
it('should define filetype', async () => {
const cb = jest.fn();
process.env.FILE_TYPE = 'jpg';
multerOptions.fileFilter({}, mockFile, cb);
expect(cb).toHaveBeenCalled();
expect(cb).toHaveBeenCalledTimes(1);
expect(cb()).toBeFalsy();
});
测试用例获得成功。但覆盖范围和线路仍然相同
【问题讨论】:
-
请更改标题,以便未来的搜索者可以从中受益。想象一下,如果您遇到这个问题,您会在搜索引擎中添加什么?
-
另请注意,代码覆盖率与通过的测试数量无关。它会告诉您测试涵盖了哪些代码。
-
我一定会这样做的。关于测试那条线有什么帮助吗?
-
即使是很小的帮助或建议也会很有帮助。请帮忙
标签: javascript node.js unit-testing jestjs nestjs