茉莉花间谍猫鼬模型

时间:2018-07-06 10:10:32

标签: node.js mongoose jasmine

我正在使用Jasminesupertest测试express路由。但是,我的测试中的spyOn似乎无法正常工作。

我的测试:

const request = require('supertest');
const app = require('../../app');

describe('Test external system router: ', () => {
    const ExternalSystem = require('../../models/externalSystem');
    let token;

    beforeAll(async () => {
        let res = await request(app)
            .post('/api/login')
            .send({
                username: 'ADMIN',
                password: 'Sit11111'
            }).catch(err => {
                console.log(err);
                return;
            });
        if (res && res.body) 
            token = res.body.token;
    })

    it('POST saveExternalSystem ', async () => {
        spyOn(ExternalSystem, 'create').and.callThrough();

        let param = {
            sysName: 'TEST2',
            accessKey: 'TESTKEY',
            ipaddr: null,
            params: null,
            remark: 'A remark'
        };

        const response = await request(app).post('/api/saveExternalSystem').set('authorization', 'Bearer ' + token).send(param);
        expect(response.status).toBe(200);
        expect(ExternalSystem.create).toHaveBeenCalledWith(param);
    });
});

API:

exports.saveExternalSystem = async (req, res) => {
    try {
        let es = await ExternalSystem.findOne({ sysName: req.body.sysName }).exec();
        if (es) {
            logger.info(`${req.payload.user.username} add external system fail: ${cst.EXTERNAL_SYSTEM_NAME_EXIST}`);
            res.json({ 'message': cst.EXTERNAL_SYSTEM_NAME_EXIST });
            return;
        }

        let newEs = new ExternalSystem(req.body);

        // do some stuff

        let raw = await newEs.save();
        logger.info(`${req.payload.user.username} add external system success`);
        res.status(200).json(raw);
    } catch (err) {
        logger.error(`${req.payload.user.username} add external system fail with server error: ${err}`);
        res.status(500).end();
    }
}

实际上已成功创建了新实体,状态码为200。但控制台显示:

Failures:
1) Test external system router:  POST saveExternalSystem
  Message:
    Expected spy create to have been called with [ Object({ sysName: 'TEST2', accessKey: 'TESTKEY', ipaddr: null, params: null, remark: 'A remark' }) ] but it was never called.

有人可以指出错误吗?

0 个答案:

没有答案