使用React Jest时面临状态码400

zi8p0yeb  于 12个月前  发布在  Jest
关注(0)|答案(1)|浏览(122)

我正在学习使用React中的Jest进行单元测试。当我的API返回给我响应时,我想测试状态200和400。但是第一个是通过测试,但第二个是面临请求失败,状态代码400错误ant然后第二个案例失败。为什么我会面临这个?我拿了一组我的案例,我用axios-mock-adapter模拟了我的axios get方法。你认为问题在哪里?我应该怎么做?这是我的示例代码。
UserService.test.ts:

import { ACCOUNT_SETTINGS } from '../../core/constants/apiEndpoints'
import mockServiceInstance from '../__mocks__/MockService'
import { fetchUsersMockData, userClaimsTreeMockData } from "../__mocks__/UserServiceMockData";
import axios from "axios";
import MockAdapter from "axios-mock-adapter";

afterEach(() => {
    jest.clearAllMocks()
});

const mock = new MockAdapter(axios);

// roles/list?PageIndex=0&PageSize=3
describe('fetchAllUsers method', () => {
    let url : string = `${ACCOUNT_SETTINGS.PAGED_LIST}?PageIndex=${0}&PageSize=${3}`;
    
    it("get is succesfull", async () => {
        const mockData = {
            result: fetchUsersMockData,
            error: null,
            isSuccessful: true
        }

        mock.onGet(url).reply(200, mockData);
        const { data } = await axios.get(url)
        expect(data.result).toStrictEqual(fetchUsersMockData);

    })

    it("get has error", async () => {
        mock.onGet(url).reply(400); 
        const { status} = await axios.get(url) // here is error line
    })

})

字符串
我的示例模拟数据:

fetchUsersMockData = {
    pageIndex: 0,
    pageSize: 3,
    totalCount: 8,
    totalPages: 1,
    items: [
        {
            id: uuidv4(),
            username: "[email protected]",
            name: "Scot",
            surname: "Lawson",
            email: "[email protected]",
            phoneNumber: "03212342345",
            isActive: true,
            isLocked: false,
            timeZone: "Europe/Istanbul"
        }
    ]
}

cnjp1d6j

cnjp1d6j1#

将错误测试场景 Package 在try...catch块中
解决方法:

try {
  it("get has error", async () => {
        mock.onGet(url).reply(400); 
        const { status} = await axios.get(url) // here is error line
    })
}catch(e){
   code///
}

字符串
更多关于错误处理

相关问题