如何在jest和Typescript中测试一个类的方法

mwg9r5ms  于 2023-10-14  发布在  Jest
关注(0)|答案(1)|浏览(116)

我正在使用spies来测试一个类中的javascript方法。在User模型中,我创建了一个UGC静态方法,它检查User类型的对象数组,如果找到,则返回User。

static comparePasswordHash = async (hash: string, plainPassword: string) => await bcrypt.compare(plainPassword, hash);

  static getUser = async (email: string, passwordPlain: string): Promise<User | Error> => {
    try {
        const userData: any = await readSmallRecord(FileNames.Users);
        const users: User[] = JSON.parse(userData);

        const user = users.find(user => user.email === email.toLowerCase());

        if (!user) return new Error('User not found');

        const matchPassword = await this.comparePasswordHash(user.password, passwordPlain);
        if (!matchPassword) return new Error('Invalid credentials');
        return user;

    } 
    catch (error) {
        console.error(error);
        return new Error('Failed to fetch user data');
    }
  };

在测试文件中,我模拟了这个模块,设置间谍监视User类中的getUser方法,创建一个新的User。

import User from "./user.model";
jest.mock('./user.model');

describe('Testing user class', () => {

    it("Should return a user object if a record will be found", async () => {
        const mockGetUser = jest.spyOn(User, 'getUser');
        const mockedUser = new User('Testing value', 'testing', '[email protected]');
    
        mockGetUser.mockResolvedValue(mockedUser);
        console.log(mockedUser);
    
        const result = await User.getUser('[email protected]', 'testing');
    
        // Assert that the result is the same as the mocked user object
        expect(result).toEqual(mockedUser);

    
        // Restore the mock after the test
        mockGetUser.mockRestore();
    });
    
});

结果和模拟的用户是数组中的空对象.我做错了什么?

inn6fuwd

inn6fuwd1#

你的测试总是通过的原因是你模拟的结果总是等于你提供的数据:

const mockGetUser = jest.spyOn(User, 'getUser');
const mockedUser = new User('Testing value', 'testing', 'te[email protected]');
mockGetUser.mockResolvedValue(mockedUser);

然后对相同的值进行测试:

const result = await User.getUser('[email protected]', 'testing');
// Assert that the result is the same as the mocked user object
expect(result).toEqual(mockedUser);

这意味着每当它执行getUser时,结果值总是mockedUser,这与result相同。
如果你想正确地测试你的类,你可以模拟用户记录或者readSmallRecord方法而不是getUser
下面是一个使用readSmallRecord mock的例子:
假设:
1.该方法存储在名为./user.method的文件中

  1. User类具有以下构造函数或类似的构造函数(因为您没有提供完整的代码):
constructor(name: string, passwordPlain: string, email: string) {
       this.name = name
       this.email = email
       this.passwordPlain = passwordPlain
}

这一行帮助您设置用户记录,以便您可以测试记录中是否存在某个用户。

let mockRecordValue = ''
jest.mock('./user.method', () => ({
    readSmallRecord: () => mockRecordValue,
}))

然后,您可以按如下方式添加测试套件:

describe('Testing user class', () => {
    it("Should return a user object if a record will be found", async () => {
        mockRecordValue = '[{ "email": "[email protected]", "name": "Testing value", "passwordPlain": "testing" }]'
        const mockedUser = new User('Testing value', 'testing', '[email protected]');
        let result = await User.getUser('[email protected]', 'testing');
    
        // Assert that the result is the same as the mocked user object
        expect(result).toEqual(mockedUser);

        mockRecordValue = '[{ "email": "[email protected]", "name": "Testing value", "passwordPlain": "testing" }]'
        result = await User.getUser('[email protected]', 'testing');
        
        // Assert that the result throws error on user not found
        expect(result).toEqual(Error('User not found'))

        mockRecordValue = 'invalidJSON'
        result = await User.getUser('[email protected]', 'testing');

        // Assert that the result throws error on fetching user data 
        expect(result).toEqual(Error('Failed to fetch user data'))
    });
    
});

相关问题