我创建了将数据发送到后端的服务,数据由用户在 UI 中填充。用户也可以上传任何文件以将其发送到后端。我正在尝试用茉莉弹珠测试此功能。
这是我的服务代码:
export class FormSubmitService {
constructor(private http: HttpClient) {}
public submit(data, attachments) {
const observables = [
...attachments.map((file) => this.uploadAttachment(file)),
];
return forkJoin(...observables)
.pipe(
defaultIfEmpty([]),
map((tokens) => {
return tokens.map((tokenObj) => tokenObj.attachment_token);
}),
switchMap((tokens: string[]) => {
const formData = {
data,
attachments: tokens,
};
return this.submitForm(formData);
}),
);
}
private uploadAttachment(attachment: File) {
const attachmentData: FormData = new FormData();
attachmentData.append('attachment', attachment, attachment.name);
return this.http.post(
'/some/form/endpoint/attachments',
attachmentData,
);
}
private submitForm(userData: UserData) {
return this.http.post(
`/some/form/endpoint/form`,
userData,
);
}
}
如果用户添加一个或多个附件,那么在我将用户数据发送到后端之前,我需要将每个附件上传到后端以获取每个附件的令牌,然后我将其存储在数组中。我正在这样做forkJoin()
,等到所有附件都上传完毕,然后switchMap
用于提交用户数据。
这是我的两个测试用例(一个工作,一个不工作):
describe('SubmitFormData', () => {
let service: FormSubmitService;
let http: jasmine.SpyObj<HttpClient>;
beforeEach(() => {
http = jasmine.createSpyObj('HttpClient', ['post']);
service = new FormSubmitService(http);
});
describe('#submit', () => {
const file = new File([''], 'filename', { type: 'image/png' });
const attachments = [file];
const data = {
name: 'name',
description: 'description',
};
// NOT WORKING!
it('submit with attachment', () => {
const expected = cold('-a--b-', { a: ['token'], b: { id: 'id_123' } }); // FAIL!
// const expected = cold('----'); // SUCCESS!
http.post.and.returnValues(
cold('-a-', { a: [{ attachment_token: 'token' }] }),
cold('-a-', { a: { id: 'id_123' } }),
);
const output = service.submit(data, attachments);
expect(output).toBeObservable(expected);
expect(http.post).toHaveBeenCalled();
});
// WORKING!
it('submit without attachment', () => {
const response = {
id: 'id_123',
};
const expected = cold('-a-', { a: response });
http.post.and.returnValues(
cold('-a-', { a: { id: 'id_123' } }),
);
const output = service.submit(data, []);
expect(output).toBeObservable(expected);
expect(http.post).toHaveBeenCalled();
});
});
});
测试表单数据在哪里没有附件是成功的,但是测试表单数据在哪里有附件失败。
失败的错误信息:
✖ 提交附件 HeadlessChrome 71.0.3578 (Mac OS X 10.14.2) 错误:预期 $.length = 0 等于 2。预期 $[0] = 未定义等于 Object({ frame: 10, notification: Notification({ kind :'N',值:['token'],错误:未定义,hasValue:真})})。预期 $[1] = undefined 等于 Object({ frame: 40, notification: Notification({ kind: 'N', value: Object({ id: 'id_123' }), error: undefined, hasValue: true }) } )。
似乎output
is not emitting observable in failed test and is undefined
,但问题是 - 为什么?因为在另一个测试中,它在不发送附件和使用forkJoin()
.
任何人都知道为什么会这样?谢谢!