我如何测试猫鼬预保存钩中的语句

我不熟悉测试,并且希望获得良好的代码覆盖率。

我的用户模型上有一个预保存的钩子,用于处理对哈希值进行哈希处理的操作,现在我只希望在修改了密码字段后才能运行该钩子。

如何测试if语句?是保存用户,更新用户然后再次保存并测试密码的情况吗?

另一个问题。最佳做法是什么?要将其用作用户模型上的预保存钩子或方法?

UserSchema.pre('save',async function(next) {
  // Only run this function if password was modified
  if (!this.isModified('password')) return next();

  // Hash the password
  this.password = await bcrypt.hash(this.password,12);

  // Remove passwordConfirm field
  this.passwordConfirm = undefined;

  next();
});
xiangxiangdetang 回答:我如何测试猫鼬预保存钩中的语句

这是单元测试解决方案:

index.js

import { Schema } from 'mongoose';
import bcrypt from 'bcrypt';

const UserSchema = new Schema();

UserSchema.pre('save',userPreSaveHook);

export async function userPreSaveHook(next) {
  // Only run this function if password was modified
  if (!this.isModified('password')) return next();

  // Hash the password
  this.password = await bcrypt.hash(this.password,12);

  // Remove passwordConfirm field
  this.passwordConfirm = undefined;

  next();
}

index.spec.js

import { userPreSaveHook } from './';

describe('userPreSaveHook',() => {
  test('should execute next middleware when password is modified',async () => {
    const mNext = jest.fn();
    const mContext = {
      isModified: jest.fn()
    };
    mContext.isModified.mockReturnValueOnce(false);
    await userPreSaveHook.call(mContext,mNext);
    expect(mContext.isModified).toBeCalledWith('password');
    expect(mNext).toBeCalledTimes(1);
  });

  test('should has password and remove passwordConfirm field',async () => {
    const mNext = jest.fn();
    const mContext = {
      isModified: jest.fn(),passwordConfirm: 'aaa',password: '123456'
    };
    mContext.isModified.mockReturnValueOnce(true);
    await userPreSaveHook.call(mContext,mNext);
    expect(mContext.isModified).toBeCalledWith('password');
    expect(mNext).toBeCalledTimes(1);
    expect(mContext.passwordConfirm).toBeUndefined();
    expect(mContext.password).not.toBe('123456');
  });
});

覆盖率100%的单元测试结果:

 PASS  src/stackoverflow/58701700/index.spec.js (12.23s)
  userPreSaveHook
    ✓ should execute next middleware when password is modified (9ms)
    ✓ should has password and remove passwordConfirm field (295ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.js |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed,1 total
Tests:       2 passed,2 total
Snapshots:   0 total
Time:        12.689s,estimated 14s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58701700

本文链接:https://www.f2er.com/3163460.html

大家都在问