"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"test": "jest",
"testa": "jest --watchAll"
}
$ npm install --save-dev @testing-library/react-hooks
/**
* @jest-environment jsdom
*/
import * as React from 'react'
import axios from 'axios'
import '@testing-library/jest-dom/extend-expect'
import { render, screen, fireEvent } from '@testing-library/react'
import Form from '../../src/components/form'
jest.mock('axios')
// 简单校验input失去焦点是如果没有值是不是会提示'用户名不可以为空'的信息
test('form表单用户名验空', () => {
// 渲染表单组件
render(<Form />)
// 获取dom
const name = screen.getByTestId('name')
// 模拟input失去焦点事件
fireEvent.blur(name)
// 获取抱错信息dom
const nameErrorMsg = screen.getByTestId('nameErrorMsg')
// 断言 抱错信息dom的文案是不是 '用户名不可以为空'
expect(nameErrorMsg).toHaveTextContent('用户名不可以为空')
})
// 通过`axios`mock提交表单的接口返回数据
test('form表单提交数据', async () => {
// mock数据 将入参name, password 拼接成token字段返回 组件中将返回的token存储到localStorage中
axios.post.mockImplementationOnce((url, body) => {
const { name, password } = body?.data
const token = `token=${name}+${password}`
return Promise.resolve({ data: token })
})
// 渲染组件
render(<Form />)
// 将`admin`赋值到用户名字段
const name = screen.getByTestId('name')
fireEvent.change(name, { target: { value: 'admin' } })
// 将`123456`赋值到密码字段
const password = screen.getByTestId('password')
fireEvent.change(password, { target: { value: '123456' } })
// 获取提交按钮
const submit = screen.getByTestId('submit')
// 模拟按钮点击事件 异步提交数据
await fireEvent.click(submit)
// 断言localStorage中`_token`字段是否有值
expect(window.localStorage.getItem('_token')).not.toBeNull()
})
欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/) | Powered by Discuz! X3.2 |