it('mock function should be call two times', () => { // 把這個 mock 當成 callback const mockFunction = jest.fn((x) => x + 1) forEach([1, 2, 3], mockFunction) // mock 應該要被執行三次 expect(mockFunction.mock.calls.length).toBe(3) })
檢查 Mock 是怎麼被呼叫的
toHaveBeenCalledWith
1 2 3 4 5 6 7
it('mock function should be call with an argument', () => { const mockFunction = jest.fn((x) => x + 1) forEach(['A'], mockFunction) // 可以想成是這樣:mock.call(this, 'A') // 就是 mock 是怎麼被呼叫的意思 expect(mockFunction).toHaveBeenCalledWith('A') })
檢查 Mock 每一次是怎麼被呼叫的
toHaveBeenNthCalledWith
1 2 3 4 5 6 7 8
it('mock function should be call with each element', () => { const mockFunction = jest.fn((x) => x + 1) forEach(['A', 'B', 'C'], mockFunction) // mock 的每一次是怎麼被 call 的 expect(mockFunction).toHaveBeenNthCalledWith(1, 'A') expect(mockFunction).toHaveBeenNthCalledWith(2, 'B') expect(mockFunction).toHaveBeenNthCalledWith(3, 'C') })