模拟es6类方法

时间:2019-02-11 16:50:39

标签: node.js unit-testing express jestjs

我正在测试Express应用,并且我具有以下文件:

app.js

const express = require('express');
const path = require('path');

const apiRouter   = require('./api');

const app = express();       
app.use('/api',apiRouter);


module.exports = app;

api.js

const Router = require( 'express').Router;
const CompanyController =require( './CompanyController');

const router = Router();

router.route('/company/registration').post(CompanyController.register);

module.exports=router;

CompanyController.js

class CompanyRegistration {
    constructor() {}


    static async register(req, res) {
        //some implementations
       //if successfull returns status code 200 or 422 if cant process

} 

registration.js

import Request from 'supertest';
import app from   './app';
import CompanyController from './CompanyController';

const mockComp = jest.fn();
CompanyController.mockImplementation(()=>{
    return {
        register:mockComp
    }
});


it("should work",()=>{


    return Request(app).post("/api/company/registration").then(response => {
        expect(response.statusCode).toBe(200)
    });
}); 

我想做的是在CompanyController中模拟register方法并更改实现,以使其返回状态码200,但出现错误:

  

TypeError:_CompanyController.default.mockImplementation不是   功能

如何正确实施此方法?

1 个答案:

答案 0 :(得分:0)

如果您想使用mockImplementation,则需要告知Jest CompanyController必须被嘲笑(如here所述):

import CompanyController from './CompanyController';
jest.mock('./CompanyController'); // you miss this line
const mockComp = jest.fn();
CompanyController.mockImplementation(()=>{
    return {
        register:mockComp
    }
});