【问题标题】:How to mock async method with jest in nodejs如何在nodejs中用玩笑模拟异步方法
【发布时间】:2021-09-25 21:38:13
【问题描述】:

我有下面提到的文件

|_ utils.js |_methods.js

我正在对rest.js方法进行单元测试,文件内容是

methods.js

import Express from 'express'
import { add_rec } from './utils'

export const create_rec = () => async (req: Express.Request, res: Express.Response) => {
    const rec_body = req.body.rec

    return add_rec(rec_body)
        .then((ret) => res.status(201).send(ret))
        .catch((e) => {
            res.status(500).send({ message: e.message })
        })
}

如何模拟 add_rec 异步函数,以便我可以对我的 create_rec 进行单元测试 功能

我正在尝试以下面的方式测试 create_rec,但它不允许我模拟 add_rec 方法

mport { getMockReq, getMockRes } from '@jest-mock/express'
import { add_rec } from './utils'
jest.mock('./utils')

describe('test create_rec method valid param', () => {
    it('test create_rec method', async () => {
        const req = getMockReq({
            body: {
                rec: {},
            },
        })
        const { res } = getMockRes<any>({
            status: jest.fn(),
            send: jest.fn(),
        })
        add_rec.mockResolved({}) // this line is giving error in fact it is not mocked i think
        await create_rec()(req, res)
        expect(res.status).toHaveBeenCalledTimes(1)
        expect(res.send).toHaveBeenCalledTimes(1)
    })
})

请帮帮我。

【问题讨论】:

    标签: node.js typescript express unit-testing jestjs


    【解决方案1】:

    你的代码几乎是正确的,除了你需要对mock方法的TS类型做一些处理,你可以使用类型断言。

    例如

    methods.ts:

    import Express from 'express';
    import { add_rec } from './utils';
    
    export const create_rec = () => async (req: Express.Request, res: Express.Response) => {
      const rec_body = req.body.rec;
    
      return add_rec(rec_body)
        .then((ret) => res.status(201).send(ret))
        .catch((e) => {
          res.status(500).send({ message: e.message });
        });
    };
    

    utils.ts:

    export async function add_rec(params): Promise<any> {
      console.log('real implementation');
    }
    

    methods.test.ts:

    import Express from 'express';
    import { create_rec } from './methods';
    import { add_rec } from './utils';
    
    jest.mock('./utils');
    
    describe('68419899', () => {
      test('should pass', async () => {
        (add_rec as jest.MockedFunction<any>).mockResolvedValueOnce({});
        const req = ({ body: { rec: {} } } as unknown) as Express.Request;
        const res = ({ status: jest.fn().mockReturnThis(), send: jest.fn() } as unknown) as Express.Response;
        await create_rec()(req, res);
        expect(add_rec).toBeCalledWith({});
        expect(res.status).toBeCalledWith(201);
        expect(res.send).toBeCalledWith({});
      });
    });
    

    测试结果:

     PASS  examples/68419899/methods.test.ts (8.659 s)
      68419899
        ✓ should pass (5 ms)
    
    ------------|---------|----------|---------|---------|-------------------
    File        | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    ------------|---------|----------|---------|---------|-------------------
    All files   |   81.82 |      100 |   66.67 |      75 |                   
     methods.ts |   88.89 |      100 |      80 |   83.33 | 10                
     utils.ts   |      50 |      100 |       0 |      50 | 2                 
    ------------|---------|----------|---------|---------|-------------------
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        9.198 s
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-27
      • 2021-06-26
      • 2019-07-09
      • 1970-01-01
      • 2018-02-22
      • 1970-01-01
      • 2019-03-23
      相关资源
      最近更新 更多