简体   繁体   中英

jest.mock - how to check that function inside function has been called

This is a part of my app:

import validationSchema from "./../_validation/report";
const reportModel = require("../models/report");


ctrl.addReport = async (req, res) => {
  const { body } = req;

  try {
    const validatedData = await validationSchema.validate(body);
    const report = await reportModel(req.dbConnection).addReport(validatedData);

    // something more
  } catch (err) {
    throw boom.badRequest(err);
  }
};

module.exports = ctrl;

I would like to write some unit test but I want to test that addReport from reportModel has been called with the correct argument.

To mock reportModel I use jest.mock like this:

const reportModel = require("../models/report");

jest.mock('../models/report', () => {
  return () => {
    return {
      addReport: jest.fn(() => {
        return true
      })
    }
  }
});

// do some tests and call function which call addReport from reportModel

expect(reportModel().addReport).toHaveBeenCalledTimes(1);

I've got 0. How can I check that addReport from reportModel has been called?

You didn't mock ./models/report module correctly. Here is the solution:

ctrl.js :

import validationSchema from './_validation/report';
import reportModel from './models/report';

const ctrl = {};

ctrl.addReport = async (req, res) => {
  const { body } = req;
  const validatedData = await validationSchema.validate(body);
  const report = await reportModel(req.dbConnection).addReport(validatedData);
};

module.exports = ctrl;

./models/report.js :

function reportModel(connection) {
  return {
    async addReport(data) {
      console.log('addReport');
    },
  };
}
export default reportModel;

./_validation/report.js :

const validationSchema = {
  validate(body) {
    return body;
  },
};

export default validationSchema;

ctrl.test.js :

import reportModel from './models/report';
const ctrl = require('./ctrl');

jest.mock('./models/report', () => {
  const mReportModel = {
    addReport: jest.fn(() => true),
  };
  return jest.fn(() => mReportModel);
});

describe('59431651', () => {
  it('should pass', async () => {
    const mReq = { body: 'mocked data', dbConnection: {} };
    const mRes = {};
    await ctrl.addReport(mReq, mRes);
    expect(reportModel).toBeCalledWith(mReq.dbConnection);
    expect(reportModel(mReq.dbConnection).addReport).toHaveBeenCalledTimes(1);
  });
});

Unit test result with coverage report:

 PASS  src/stackoverflow/59431651/ctrl.test.js
  59431651
    ✓ should pass (7ms)

----------------------|----------|----------|----------|----------|-------------------|
File                  |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------------------|----------|----------|----------|----------|-------------------|
All files             |      100 |      100 |      100 |      100 |                   |
 59431651             |      100 |      100 |      100 |      100 |                   |
  ctrl.js             |      100 |      100 |      100 |      100 |                   |
 59431651/_validation |      100 |      100 |      100 |      100 |                   |
  report.js           |      100 |      100 |      100 |      100 |                   |
----------------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.682s, estimated 11s

Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59431651

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM