输入类型文件的反应式上传表单的开玩笑测试用例<输入类型= "file" 表单控件名称= "userslist" > (角度 7)



我在角度 7 中实现了反应式上传表单。表单工作正常,但无法添加单元测试用例,因为patchValue或 setValue 不允许我们在输入类型文件中设置虚拟数据。谁能建议我使用reative形式为输入类型文件编写一个测试用例?我想测试importUsers()-

import-users.component.html

<form [formGroup]="importForm">
<input type="file" (change)="fileEvent($event)" name="userslist" formControlName="userslist">
< /form>

import-users.component.ts -

selectedFile: any;
importForm = new FormGroup({
userslist: new FormControl(null, [Validators.required]),
});
fileEvent(event: any) {
const fileData = event.target.files;
this.selectedFile = fileData[0];
}
importUsers() {
if (this.importForm.invalid) {
return throwError(new Error('INVALID_FORM'));
}
const fd = new FormData();
fd.append('usersFile', this.selectedFile);
this.userService.importUsers({ body: fd })
.subscribe(() => {
this.closeModal();
});
}
...

import-users.component.spec.ts

it('should import users', () => {
const file = { name: 'user.csv', type: 'text/csv' } as File;
jest.spyOn(userService, 'importUsers');
component.importForm.patchValue({
userslist: file,
});
component.importUsers();
expect(userService.importUsers).toHaveBeenCalled();
});

使用上面的测试用例,我收到以下错误消息 -

InvalidStateError:此输入元素接受文件名,该文件名只能以编程方式设置为空字符串。

我能够按照此处的说明解决此错误 如何使用 Jest 和 vue/test-utils 测试输入文件

describe('fileInput',() => {
let fileInput: HTMLElement;
let uploadButton: HTMLElement;
let fileInputFilesGet;
let fileInputValueGet;
let fileInputValueSet;
let fileInputValue = '';
const fileFixture: Partial<File> = {
name: 'myimage.png', 
lastModified: 1580400631732, 
size: 703786, 
type: 'image/png'
};
beforeEach(async () => {
const { getByLabelText, getByText } = render (
<FileInput/> 
);
fileInput = getByLabelText('File Input');
uploadButton = getByText('UPLOAD');
fileInputFilesGet = jest.fn();
fileInputValueGet = jest.fn().mockReturnValue(fileFixture);
fileInputValueSet = jest.fn().mockImplementation(v => {
fileInputValue = v;
});
Object.defineProperty(fileInput, 'files', {
get: fileInputFilesGet
});
Object.defineProperty(fileInput, 'value', {
get: fileInputValueGet,
set: fileInputValueSet
});
});
it('upload file when click on upload button', async() => {
fileInputValue = 'myimage.png';
fileInputFilesGet.mockReturnValue([fileFixture]);
await act(async () => {
fireEvent.click(uploadButton);
});
....
});

最新更新