关于玩笑嘲笑我不了解的问题

时间:2019-01-30 23:53:05

标签: angular jestjs

我是测试的新手,我确定有些事情我做得不好

我要测试Angular服务:

UserService.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”和...。我完全不理解为什么^^

1 个答案:

答案 0 :(得分:2)

Mock Function会记住对它的所有呼叫。

在这种情况下,api.put在第一次测试期间被称为

由于尚未清除它,因此它仍然报告在第二次测试中选中它时被调用。

使用mockFn.mockClear()清除以前对模拟函数的所有调用:

test('should not make an api call if camera error', async () => {

    api.put.mockClear();  // clear the mock

    cameraService.selectPicture.mockImplementation(() => { throw new Error(); });

    await userService.changePicture();

    expect(api.put).not.toBeCalled();  // SUCCESS
});