Skip to main content

expect 可以驗証什麼

expect 使用說明

  1. 一定要用 mock function 才可以
expect([這個裡面一定要是 mock function])
ex:
jest.spyOn(apiService, 'post').mockReturnValue(of({}));
jest.spyOn(component.dialog, 'open');

expect(apiService.post).toHaveBeenCalledWith('/subscribe', { email, tdc_id, event_category: 'Homepage' });

expect(component.dialog.open).toHaveBeenCalledWith(GeneralDialogComponent, {
data: {
color: 'bg-main-color',
title: 'emarket.newsletter.subscribe_success.title',
description: 'emarket.newsletter.subscribe_success.content',
solidBtnText: 'emarket.newsletter.subscribe_success.btn.main',
},
});

以此篇文章的寫法為主

expect.objectContaining(object)
expect.toHaveBeenCalledWith(arg1, arg2, ...)

objectContaining(object)

匹配遞歸地匹配預期屬性的任何接收對象。也就是說,預期對象是接收對象的子集。因此,它匹配所接收的對象,該對象包含不屬於預期對象的屬性。

與期望對象中的文字屬性值不同,您可以使用matchers、expect.anything()等等。

假設我們希望使用事件對象調用onPress函數,我們需要驗證的是事件是否有event.x屬性和y屬性。我們可以這樣做:

test('onPress gets called with the right thing', () => {
const onPress = jest.fn();
simulatePresses(onPress);
expect(onPress).toBeCalledWith(
expect.objectContaining({
x: expect.any(Number),
y: expect.any(Number),
}),
);
});

TDC 中常見的用法

const dataLayerSpy = jest.spyOn(analyticsService, 'dataLayer');
...
expect(dataLayerSpy).toBeCalledWith(
expect.objectContaining({
event: 'Market',
eventValue: `Winbond / Product / W25 / Restock Notify`,
})
); // 在經過一連串的 function 後所打的 event 是不是用期待的參數來傳

toHaveBeenCalledWith(arg1, arg2, ...)

如果参数列表与spy调用时的参数相匹配,则返回true。

// 該 mock 函式至少被呼叫一次,並且帶有特定的參數
expect(mockFunc).toHaveBeenCalledWith(arg1, arg2);
const api = jest.spyOn(apiService, 'post').mockReturnValue(of({}));
expect(api).toHaveBeenCalledWith('/subscribe', { email, tdc_id, event_category: 'Homepage' });
expect(analyticsSpy).toHaveBeenCalledWith(
expect.objectContaining({
event: 'Footer',
eventCategory: 'Homepage',
eventValue: 'Newsletter Subscription / Submit Successfully',
})
);

待整理

使用匹配與客製化匹配(Custom Matchers)

方便易用的方法:

// 該 mock 函式至少被呼叫過一次
expect(mockFunc).toHaveBeenCalled();

// 該 mock 函式至少被呼叫一次,並且帶有特定的參數
expect(mockFunc).toHaveBeenCalledWith(arg1, arg2);

// 該 mock 函式最後一次被呼叫時帶有特定的參數
expect(mockFunc).toHaveBeenLastCalledWith(arg1, arg2);

// All calls and the name of the mock is written as a snapshot
expect(mockFunc).toMatchSnapshot();

使用原生的 mock 物件做比對:

// 該 mock 函式至少被呼叫過一次
expect(mockFunc.mock.calls.length).toBeGreaterThan(0);

// 該 mock 函式至少被呼叫一次,並且帶有特定的參數
expect(mockFunc.mock.calls).toContainEqual([arg1, arg2]);

// 該 mock 函式最後一次被呼叫時帶有特定的參數
expect(mockFunc.mock.calls[mockFunc.mock.calls.length - 1]).toEqual([arg1, arg2]);

// 該 mock 函式最後一次被呼叫時的第一個參數是 42
// (note that there is no sugar helper for this specific of an assertion)
expect(mockFunc.mock.calls[mockFunc.mock.calls.length - 1][0]).toBe(42);

// A snapshot will check that a mock was invoked the same number of times,
// in the same order, with the same arguments. It will also assert on the name.
expect(mockFunc.mock.calls).toEqual([[arg1, arg2]]);
expect(mockFunc.getMockName()).toBe('a mock name');