【发布时间】:2019-06-24 08:52:29
【问题描述】:
我是测试新手,我确定有些事情我做得不好
我想测试一个 Angular 服务:
用户服务.ts
import { Injectable } from '@angular/core';
import { API } from '@app-commons/core/API';
import { AuthService } from '@app-commons/services/AuthService';
import { CameraService } from '@app-commons/services/CameraService';
import { MessageController } from '@app-commons/controllers/MessageController';
@Injectable()
export class UserService {
public constructor(private api: API,
private auth: AuthService,
private cameraService: CameraService,
private message: MessageController) {}
public async changePicture() {
try {
const imgData = await this.cameraService.selectPicture();
const response = await this.api.put(`user/picture`, { picture: imgData });
}
catch (err) {
this.message.warningToast("Erreur lors de l'envoie de votre image, vous pouvez réessayer.", 3000);
}
this.message.okAlert('Super !', 'Votre image sera visible dans quelques instants !');
}
}
这是我的测试
UserService.spec.ts
import { UserService } from './UserService';
const api: any = {
get: jest.fn(),
put: jest.fn()
};
const auth: any = {};
const cameraService: any = {
selectPicture: jest.fn()
};
const messageController: any = {
warningToast: jest.fn(),
okAlert: jest.fn()
};
const userService = new UserService(api, auth, cameraService, messageController);
describe('UserService : changeImage', () => {
test('should take a picture, upload it and display a message', async () => {
cameraService.selectPicture.mockReturnValueOnce('base64Image');
await userService.changePicture();
expect(messageController.okAlert).toBeCalled();
});
test('should not make an api call if camera error', async () => {
cameraService.selectPicture.mockImplementation(() => { throw new Error(); });
await userService.changePicture();
expect(api.put).not.toBeCalled();
});
});
第一次测试通过,但第二次测试出错。
● UserService : changeImage › should not use api if camera error
expect(jest.fn()).not.toBeCalled()
Expected mock function not to be called but it was called with:
["user/picture", {"picture": "base64Image"}]
69 | await userService.changePicture();
70 |
> 71 | expect(api.put).not.toBeCalled();
| ^
72 | // expect(messageController.warningToast).toBeCalled();
73 | });
74 |
我们可以清楚地看到,它在第二个测试中,但是它调用了第一个中定义的参数的方法:'base64Image'和......我完全不明白为什么^^
【问题讨论】: