如何测试getServerSideProps的最终return语句?返回结果为undefined
解决getServerSideProps测试中customerGroup返回undefined的问题
问题根源拆解
你的测试出现customerGroup为undefined,核心原因有三个:
- 类型断言错误:原函数最终返回的是包含
ok、status、data的对象,不是你断言的{ props: ... }结构 - 未正确mock依赖函数:
getUser和getCustomerGroup这两个异步函数没有被模拟返回预期数据,导致customerGroup.data未被赋值 - 测试入参缺失:
serverSideProps对象可能没传入必要的locale、query(shopId/groupId)、accessToken参数
正确测试方案
1. Mock依赖函数
模拟getUser和getCustomerGroup的返回值,确保它们返回ok: true的响应,并且包含有权限的用户数据、预期的客户组数据:
// 以Jest为例进行mock jest.mock('./path-to-your-api-module', () => ({ getUser: jest.fn().mockResolvedValue({ ok: true, json: jest.fn().mockResolvedValue({ data: { permissions: ['canUpdateTargetGroup'] // 确保用户具备目标权限 } }) }), getCustomerGroup: jest.fn().mockResolvedValue({ ok: true, json: jest.fn().mockResolvedValue({ data: { id: 'test-group-1', name: 'VIP客户组' } // 测试用的客户组数据 }) }) }));
2. 补全测试入参
确保传入getServerSideProps的参数包含所有必要字段:
// 构造符合要求的入参 const mockContext = { locale: 'en_US', query: { shopId: 'test-shop-1', groupId: 'test-group-1' } }; const mockAuth = { accessToken: 'valid-test-token' };
3. 修正测试断言逻辑
原函数返回的结构是{ ok: boolean, status: number, data: { customerGroup: ICustomerGroup, locale: string } },对应这个结构做断言:
it('should return customer group data when user has permissions', async () => { // 定义预期的客户组数据 const expectedCustomerGroup = { id: 'test-group-1', name: 'VIP客户组' }; // 调用目标函数 const result = await getServerSideProps(mockContext, mockAuth) as { ok: boolean; data: { customerGroup: ICustomerGroup; locale: string }; }; // 核心断言 expect(result.ok).toBe(true); expect(result.data.customerGroup).toEqual(expectedCustomerGroup); expect(result.data.locale).toEqual('en_US'); // 验证依赖函数是否被正确调用 expect(getUser).toHaveBeenCalledWith('en_US', 'valid-test-token'); expect(getCustomerGroup).toHaveBeenCalledWith('en_US', 'valid-test-token', 'test-shop-1', 'test-group-1'); });
额外注意点
- 如果
getServerSidePropsWrapper对返回值做了额外包装(比如转换为Next.js标准的{ props: ... }结构),需要根据Wrapper逻辑调整断言结构 - 确保类型断言准确,避免因类型不匹配导致的隐性错误
内容的提问来源于stack exchange,提问作者tdimoff
相关产品推荐
相关产品推荐

