【问题标题】:Issue I don't understand about jest mockImplementation我不了解 jest mockImplementation 的问题
【发布时间】: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'和......我完全不明白为什么^^

【问题讨论】:

    标签: angular jestjs


    【解决方案1】:

    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
    });
    

    【讨论】:

    • @jeremycastelli 太棒了,很高兴听到它有帮助!
    猜你喜欢
    • 1970-01-01
    • 2020-01-21
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多