|
1 | 1 | import MessageDisplay from '@/components/MessageDisplay'
|
2 | 2 | import { mount } from '@vue/test-utils'
|
| 3 | +import { getMessage } from '@/services/axios' |
| 4 | +import flushPromises from 'flush-promises' |
| 5 | + |
| 6 | +jest.mock('@/services/axios') |
3 | 7 |
|
4 | 8 | describe('MessageDisplay', () => {
|
5 |
| - it('Calls getMessage and displays message', async () => { |
6 |
| - // mock the API call |
| 9 | + beforeEach(() => { |
| 10 | + jest.clearAllMocks() |
| 11 | + }) |
| 12 | + |
| 13 | + it('Calls getMessage once and displays message', async () => { |
| 14 | + const mockMessage = 'Hello from the db' |
| 15 | + getMessage.mockResolvedValueOnce({ text: mockMessage }) |
7 | 16 | const wrapper = mount(MessageDisplay)
|
8 |
| - // wait for promise to resolve |
9 |
| - // check that call happened once |
10 |
| - // check that component displays message |
| 17 | + |
| 18 | + await flushPromises() |
| 19 | + expect(getMessage).toHaveBeenCalledTimes(1) |
| 20 | + |
| 21 | + const message = wrapper.find('[data-testid="message"]').text() |
| 22 | + expect(message).toEqual(mockMessage) |
11 | 23 | })
|
12 | 24 |
|
13 | 25 | it('Displays an error when getMessage call fails', async () => {
|
14 |
| - // mock the failed API call |
| 26 | + const mockError = 'Oops! Something went wrong.' |
| 27 | + getMessage.mockRejectedValueOnce(mockError) |
15 | 28 | const wrapper = mount(MessageDisplay)
|
16 |
| - // wait for promise to resolve |
17 |
| - // check that call happened once |
18 |
| - // check that component displays error |
| 29 | + |
| 30 | + await flushPromises() |
| 31 | + expect(getMessage).toHaveBeenCalledTimes(1) |
| 32 | + const displayedError = wrapper.find('[data-testid="message-error"]').text() |
| 33 | + expect(displayedError).toEqual(mockError) |
19 | 34 | })
|
20 | 35 | })
|
0 commit comments