开玩笑测试:跨文件模拟函数的难度

问题描述 投票:0回答:1

我正在尝试使用 Jest 和 Supertest 为 CreateVendor 函数编写测试。我陷入了如何模拟依赖项(generateSalt、hashPassword)以正确测试函数行为的困境。我收到此错误:“提供的对象中不存在属性generateSalt。

这个简洁的陈述应该有效地解释你的困难,并为你的导师提供帮助你的背景。

控制器功能

export const CreateVendor = async (req: Request, res: Response, next: NextFunction) => {
    const { address, email, foodType, name, ownerName, password, phone, pincode } = <CreateVendorInput>req.body
    try {
        const findOne = await findVendor('', email)
        if (!findOne) {
            const bcryptSalt = await generateSalt()
            const bcryptPassword = await hashPassword(password, bcryptSalt)
            const CreateVendor = await Vendor.create({
                name: name,
                email: email,
                address: address,
                foodType: foodType,
                ownerName: ownerName,
                password: bcryptPassword,
                phone: phone,
                pincode: pincode,
                salt: bcryptSalt,
                rating: 0,
                serviceAvailable: false,
                coverImage: [],
            })
            return res.status(201).json({ "success": CreateVendor })
        } else {
            throw new BadRequestError('Vendor Already Exists', 'Admin/CreateVendor')
        }
    } catch (err) {
        next(err)
    }
}

测试文件

it('creates a new vendor successfully', async () => {
            //@ts-ignore
            const mockVendorData: CreateVendorInput = test_data.vendor
            // const mockSalt = jest.fn().mockReturnValue('mockedSalt'); // Replace with a sample salt string
            // const mockHashedPassword = jest.fn().mockResolvedValue('hashedPassword123');

            //@ts-ignore
            jest.spyOn(Vendor, 'create').mockResolvedValueOnce(mockVendorData)
            //@ts-ignore
            jest.spyOn(Vendor, 'find').mockResolvedValueOnce(null)
            // jest.mocked(generateSalt).mockImplementation(mockSalt);
            // jest.mocked(hashPassword).mockImplementation(mockHashedPassword);


            const res = await supertest(app)
                .post('/admin/vendor') // Adjust path if necessary
                .send(mockVendorData)
                .expect(201); // Expect successful creation status code
            console.log(res.body)
            expect(res.body.success).toHaveProperty('name', mockVendorData.name); // Check name in response
            expect(res.body.success).toHaveProperty('email', mockVendorData.email);
        }, 50000);

错误

CreateVendor function
    × creates a new vendor successfully (10063 ms)

  ● CreateVendor function › creates a new vendor successfully

    expected 201 "Created", got 404 "Not Found"

      91 |                 .post('/admin/vendor') // Adjust path if necessary
      92 |                 .send(mockVendorData)
    > 93 |                 .expect(201); // Expect successful creation status code
         |                  ^
      94 |             console.log(res.body)
      95 |             expect(res.body.success).toHaveProperty('name', mockVendorData.name); // Check name in response
      96 |             expect(res.body.success).toHaveProperty('email', mockVendorData.email);

      at source/__test__/controllers/AdminController.test.ts:93:18
      at source/__test__/controllers/AdminController.test.ts:8:71
      at Object.<anonymous>.__awaiter (source/__test__/controllers/AdminController.test.ts:4:12)
      at Object.<anonymous> (source/__test__/controllers/AdminController.test.ts:76:60)
      ----
      at Test._assertStatus (node_modules/supertest/lib/test.js:252:14)
      at node_modules/supertest/lib/test.js:308:13
      at Test._assertFunction (node_modules/supertest/lib/test.js:285:13)
      at Test.assert (node_modules/supertest/lib/test.js:164:23)
      at Server.localAssert (node_modules/supertest/lib/test.js:120:14)

我尝试从

generateSalt
文件导入
../../utilities.js
函数并使用
jest.spyOn
来模拟它。我提供了一个模拟实现,它始终返回盐的字符串值。

我希望测试能够通过,并且模拟的

generateSalt
函数在执行
CreateVendor
函数期间被调用一次。然而测试失败了。

node.js typescript ts-jest supertest
1个回答
0
投票

你的第一个错误是

提供的对象中不存在属性generateSalt

这意味着你的程序想要引用

generateSalt
,但它不存在。正如您所指出的,您从
generateSalt
导入了
../../utilities.js
,尽管如此,您的测试仍然失败。

但是,如果您查看您分享的错误消息,它不再抱怨

generateSalt
不存在,而是成功执行了
generateSalt
,现在失败于

                .post('/admin/vendor') // Adjust path if necessary
                .send(mockVendorData)
                .expect(201); // Expect successful creation status code

此错误告诉您供应商未成功创建。由于错误状态是 404 而不是 201,因此您的 URL 很可能是错误的。

© www.soinside.com 2019 - 2024. All rights reserved.