首页 > 解决方案 > 模拟 lodash .isEqual Nodejs Jest 框架超级测试

问题描述

我有点卡住了使用 jest 和超级测试测试 lodash 库 lodash 库

A.routes.js

import express from 'express';
const router = express.Router();
const _ = require('lodash');
router.post('/', async (req, res, next) => {
    try {
      let data = req.body
      if(!_.isEqual(data,{"hello":"hello"}){
               console.log('Not Equal') // This line is not getting covered in Code Coverage
            }
     }.catch(e=>{
      console.log(e);
  })
});

export default router;

A.route.test.js

import a from 'A.route'
import express from 'express';
import supertest from 'supertest';
let _ = require('lodash');

_.isEqual = jest.fn();

describe('API Calls', () => {
    const app = express();
    let request;

    beforeAll(() => {
        request = supertest(app);
    });

    beforeEach(()=>{
        jest.resetModules(); 
    });

test('Successful call to post /', async () => {
        const body= {
            "Hello": "Not Hello"
        };
        
        _.isEqual.mockResolvedValueOnce(false);
        await request.post('/')
            .set('Content-Type', 'application/json')
            .set('Authorization', 'authToken')
            .send(body);
        
    });
});

代码覆盖率无法覆盖 console.log('Not Equal');我尝试使用 _.isEqual.mockImplementation (()=>return false); 也尝试过 _.isEqual.mockReturnValueOnce(false)

标签: node.jsjestjsmockinglodashsupertest

解决方案


您应该测试此 API 的行为。这意味着您应该关心响应而不是实现细节。您应该传入一个输入,例如req.body,以断言结果是否符合您的预期。

既然你的代码无法执行,我就随便加一些代码来演示一下

例如

a.router.js

import express from 'express';
const router = express.Router();
const _ = require('lodash');

router.use(express.json());
router.post('/', async (req, res, next) => {
  try {
    let data = req.body;
    console.log('data: ', data);
    if (!_.isEqual(data, { hello: 'hello' })) {
      res.send('Not Equal');
    } else {
      throw new Error('Equal');
    }
  } catch (e) {
    res.send(`Error: ${e.message}`);
  }
});

export default router;

a.router.test.js

import a from './a.router';
import express from 'express';
import supertest from 'supertest';

describe('API Calls', () => {
  const app = express();
  let request;

  beforeAll(() => {
    app.use(a);
    request = supertest(app);
  });

  test('Successful call to post /', async () => {
    const body = {
      Hello: 'Not Hello',
    };
    const res = await request
      .post('/')
      .set('Content-Type', 'application/json')
      .set('Authorization', 'authToken')
      .send(body);
    expect(res.text).toEqual('Not Equal');
  });

  test('should handle error', async () => {
    const body = {
      hello: 'hello',
    };
    const res = await request
      .post('/')
      .set('Content-Type', 'application/json')
      .set('Authorization', 'authToken')
      .send(body);
    expect(res.text).toEqual('Error: Equal');
  });
});

测试结果:

 PASS  examples/67536129/a.router.test.js (8.606 s)
  API Calls
    ✓ Successful call to post / (48 ms)
    ✓ should handle error (5 ms)

  console.log
    data:  { Hello: 'Not Hello' }

      at examples/67536129/a.router.js:9:13

  console.log
    data:  { hello: 'hello' }

      at examples/67536129/a.router.js:9:13

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

推荐阅读