test('By default, randomNumber data value should be 0', () => {
const wrapper = mount(RandomNumber)
expect(wrapper.html()).toContain('<span>0</span>')
})
props 조작
test('If button is clicked, randomNumber should be between 200 and 300', async () => {
const wrapper = mount(RandomNumber, {
props: {
min: 200,
max: 300
}
})
await wrapper.find('button').trigger('click') // 버튼 클릭
const randomNumber = parseInt(wrapper.find('span').text())
expect(randomNumber).toBeGreaterThanOrEqual(200)
expect(randomNumber).toBeLessThanOrEqual(300)
})
import LoginForm from '@/components/LoginForm.vue'
import { mount } from '@vue/test-utils'
describe('LoginForm', () => {
it('emits an event with user data payload', () => {
const wrapper = mount(LoginForm)
const input = wrapper.find('input[type="text"]') // Find text input
input.setValue('Adam Jahr') // Set value for text input
wrapper.trigger('submit') // Simulate form submission
// Assert event has been emitted
const formSubmittedCalls = wrapper.emitted('formSubmitted')
expect(formSubmittedCalls).toHaveLength(1)
// Assert payload is correct
const expectedPayload = { name: 'Adam Jahr' }
expect(wrapper.emitted('formSubmitted')[0][0]).toMatchObject(expectedPayload)
})
})
import MessageDisplay from '@/components/MessageDisplay'
import { mount } from '@vue/test-utils'
import { getMessage } from '@/services/axios'
jest.mock('@/services/axios')
jest.mock('@/services/axios') : getMessage 역할을 가져와서 실제 호출이 아닌 모의 호출을 한다
import MessageDisplay from '@/components/MessageDisplay'
import { mount } from '@vue/test-utils'
import { getMessage } from '@/services/axios'
import flushPromises from 'flush-promises'
jest.mock('@/services/axios')
beforeEach(() => {
jest.clearAllMocks()
})
describe('MessageDisplay', () => {
it('Calls getMessage and displays message', async () => {
const mockMessage = 'Hello from the db'
getMessage.mockResolvedValueOnce({ text: mockMessage })
const wrapper = mount(MessageDisplay)
await flushPromises()
expect(getMessage).toHaveBeenCalledTimes(1)
const message = wrapper.find('[data-testid="message"]').text()
expect(message).toEqual(mockMessage)
})
it('Displays an error when getMessage call fails', async () => {
const mockError = 'Oops! Something went wrong.'
getMessage.mockRejectedValueOnce(mockError)
const wrapper = mount(MessageDisplay)
await flushPromises()
expect(getMessage).toHaveBeenCalledTimes(1)
const displayedError = wrapper.find('[data-testid="message-error"]').text()
expect(displayedError).toEqual(mockError)
})
})
child component stub
describe('MessageContainer', () => {
it('Wraps MessageDisplay component', () => {
const wrapper = mount(MessageContainer, {
global: {
stubs: {
MessageDisplay: '<p data-testid="message">Hello from the db!</p>'
}
}
})
const message = wrapper.find('[data-testid="message"]').text()
expect(message).toEqual('Hello from the db!')
})
})
html toContain
props 조작
input
form
api call
jest.mock('@/services/axios')
:getMessage
역할을 가져와서 실제 호출이 아닌 모의 호출을 한다child component stub