首页 > 解决方案 > 如何用笑话模拟函数.save()续集

问题描述

我想用玩笑从续集中模拟函数 .save() 。但是我在文件 user.services.test.js 中发现我的代码有错误。有人可以帮助我吗?

错误说:result.save() 不是函数。

user.services.test.js

 it('Should update user that input by ', async () => {

        let result;
        let data ;
        let dataInput =  {id : 1, username : "teguh", userPassword : "apake"};        
        user.findByPk = jest.fn(() => {
            return {username : "teguh", userPassword : "iyah", save : mockFuntion()};
        });
        data = user.findByPk();
        data.userPassword = dataInput.userPassword;
        data.save = jest.fn(() => {return {saved:true}});

        result = await service.updateUser(dataInput);
        expect(data.save).toBeCalledTimes(1);
        expect(data.userPassword).toEqual(dataInput.userPassword);
    });

用户服务.js

async updateUser(user){
        let result;
        try {
            const pass = bcrypt.hashSync(user.userPassword, 9);
            // result = await this.user.update({userPassword : pass}, {
            //     where : {username : user.username}
            // });

             result = await this.user.findByPk(user.id);
            if(result) {
                result.userPassword = pass;
                result.save();

                return result;
            }
        } catch (e) {
            logEvent.emit('APP_ERROR', {
                logTitle : '[UPDATE-USER-FAILED]',
                logMessage : e
            });

            throw new Error(e);
        }
    }

标签: node.jsexpressjestjsmockingsequelize.js

解决方案


这是一个工作示例:

user.services.ts

import bcrypt from 'bcrypt';

const logEvent = { emit(event, payload) {} };

class UserService {
  user;
  constructor(user) {
    this.user = user;
  }
  async updateUser(user) {
    let result;
    try {
      const pass = bcrypt.hashSync(user.userPassword, 9);
      result = await this.user.findByPk(user.id);
      if (result) {
        result.userPassword = pass;
        await result.save();

        return result;
      }
    } catch (e) {
      logEvent.emit('APP_ERROR', {
        logTitle: '[UPDATE-USER-FAILED]',
        logMessage: e,
      });

      throw new Error(e);
    }
  }
}
export { UserService };

user.services.test.ts

import { UserService } from './user.services';

describe('60468548', () => {
  it('should update user that input by', async () => {
    const dataInput = { id: 1, username: 'teguh', userPassword: 'apake' };
    const userModelInstanceMock = { save: jest.fn() };
    const userModelMock = { findByPk: jest.fn().mockResolvedValueOnce(userModelInstanceMock) };
    const userService = new UserService(userModelMock);
    const actual = await userService.updateUser(dataInput);
    expect(userModelMock.findByPk).toBeCalledWith(1);
    expect(userModelInstanceMock.save).toBeCalledTimes(1);
  });
});

带有覆盖率报告的单元测试结果:

 PASS  src/examples/stackoverflow/60468548/user.services.test.ts
  60468548
    ✓ should update user that input by (36ms)

------------------|----------|----------|----------|----------|-------------------|
File              |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
------------------|----------|----------|----------|----------|-------------------|
All files         |    84.62 |       50 |    66.67 |    84.62 |                   |
 user.services.ts |    84.62 |       50 |    66.67 |    84.62 |             22,27 |
------------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.78s

推荐阅读