Reputation: 11
encryptPassword.js
import { JSEncrypt } from 'jsencrypt';
export const encryptPassword = (pwd, rsaPublicKey) => {
let retVal = pwd;
try {
const encrypt = new JSEncrypt();
encrypt.setPublicKey(rsaPublicKey);
const encryptedValue = encrypt.encrypt(pwd);
retVal = !encryptedValue ? pwd : encryptedValue;
} catch (error) {
console.log('in catch ',error)
//Exception is occurred while doing password encryption
}
return retVal;
};
I'm trying to write Unit testing for the above code with jest. But not able to mock. Tried all ways, but is always going to catch block and error says that encrypt.setPublicKey is not a function
encryptPassword.test.js
import { encryptPassword } from '../encryptPassword';
import { JSEncrypt } from 'jsencrypt';
// Mocking JSEncrypt module
jest.mock('jsencrypt', () => {
const mockJSEncryptInstance = {
setPublicKey: jest.fn(),
encrypt: jest.fn().mockImplementation((pwd) => {
// Simulating encryption (just returning the input for simplicity)
return pwd;
}),
};
const mockJSEncrypt = jest.fn().mockImplementation(() => {
return mockJSEncryptInstance;
});
return { JSEncrypt: mockJSEncrypt };
});
describe('encryptPassword function', () => {
beforeEach(() => {
// Clear all instances and calls to constructor and all methods
JSEncrypt.mockClear();
});
test('should encrypt password successfully', () => {
const pwd = 'password123';
const rsaPublicKey = 'publicKey';
const encryptedPwd = encryptPassword(pwd, rsaPublicKey);
// Expect the encrypted password to be different from the original password
//expect(encryptedPwd).not.toBe(pwd);
});
});
Please help.
Upvotes: 0
Views: 44