【问题标题】:Mock lodash .isEqual Nodejs Jest Framework Super Test模拟 lodash .isEqual Nodejs Jest 框架超级测试
【发布时间】:2021-08-04 17:37:46
【问题描述】:

我在使用 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)

【问题讨论】:

  • 这通常是一个坏主意。您应该测试行为,而不是特定的实现。如果函数更改为使用 Ramda 库或另一个 isEquals,那么您的测试现在将是错误的。只模拟相关的依赖项,而不是实现细节。
  • 但是如何提高代码覆盖率.. isEqual 没有被嘲笑的每个地方,该行都没有被覆盖
  • 不要嘲笑它。通过if这样的方式调用函数。同样,您正在测试行为,而不是实现。该函数的约定是,当 some condition 得到满足时,您将获得一个输出。如果不是,你会得到另一个。如何准确地测试some condition 的具体细节是实现细节。如果你测试实现细节,你 1. 得到脆弱的测试代码,很容易被潜在无关的重构破坏。 2. 冒着从测试中得到错误结果的风险。
  • 第二个可能是个大问题。如果您正在测试 fn(age) 并且它正在使用 _.gt(age, 18) 而您只是模拟 _.gt 您可能会错过该功能正在选择有效选民并且您已经排除了所有合法允许投票的 18 岁儿童。因此正确测试是fn(17) === falsefn(18) === true,而不是/*mock _.gt to return false*/ fn(42) === false/*mock _.gt to return true*/ fn(42) === true。您不仅没有正确测试该功能,而且_.gt -> _.gte 的更正破坏了您现有的测试。
  • 好的..让我试试其他方法..

标签: node.js jestjs mocking lodash supertest


【解决方案1】:

您应该测试此 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-30
    • 2021-08-27
    • 2020-07-31
    相关资源
    最近更新 更多