Как заглушить экземпляр объекта, не объявленного в файле - PullRequest
1 голос
/ 11 октября 2019

извините, я немного новичок в модульном тестировании, так что не уверен, будет ли это невероятно очевидным или нет, в настоящее время у меня есть этот код в структуре strapi

'use strict';
const {HOST,PORT,Bucket,cfurl} = require('../../../config/consts');
const strapi             = require('strapi');
const axios              = require('axios');
const NodeCache          = require('node-cache');
const cache              = new NodeCache();

module.exports = {
  getBanner: async (ctx) => {
    let bnr;
    if(ctx.hasOwnProperty('params') && ctx.params.hasOwnProperty('_id') && ctx.params._id != 'undefined'){
      bnr = await Banner.find({stores: ctx.params._id}).limit(1);
    }
    if(!bnr || bnr.length < 1){
      bnr = await Banner.find({"store":{"$exists": false}}).limit(1);
    }  
    ctx.send(JSON.stringify(bnr));
  }
};

Я заблудился, какзаймитесь оцеплением объекта Banner, так как он не объявлен внутри файла. Это тест, который я пытался запустить, который возвращает 'ReferenceError: Баннер не определен'

const sinon = require('sinon');
const proxyquire = require('proxyquire');
const mongoose = require('mongoose');
const mocha = require('mocha');
const assert = require('chai').assert;

describe.only('Unit test: Banner Controller Test', () => {


    describe('Test getBanner', () => {
        let sandbox;
        let fns;
        before((done) => {

            sandbox = sinon.createSandbox();
            var schema = new mongoose.Schema()
            var Banner = mongoose.model('Banner', schema);
            let success = sandbox.stub(Banner, 'find').returns({hello: "there"})

            fns = proxyquire('../../api/banner/controllers/Banner', {
                success
            })
            done()
        })

        it('should return a function call with a JSON object', (done) => {
            fns.getBanner((ctx) => {
                //returns 'ReferenceError: Banner is not defined' when run
            });
            done();
        })
    })



});

Любая помощь в решении этой проблемы будет принята с благодарностью!

1 Ответ

1 голос
/ 12 октября 2019

спасибо @langgingreflex за толчок в правильном направлении, вот мой рабочий тест для тех из вас, кто может найти его полезным

describe.only('Unit test: Banner Controller Test', () => {


    describe('Test getBanner', () => {
        let sandbox;
        let fns;
        before((done) => {
            sandbox = sinon.createSandbox();
            var schema = new mongoose.Schema({name: String})
            var Banner = mongoose.model('Banner', schema);
            sandbox.stub(Banner, 'find').callsFake(() => {
                return {
                    limit: sandbox.stub().returns({hello: 'there'})
                }
            })
            global.Banner = Banner;

            fns = proxyquire('../../api/banner/controllers/Banner', {

            })
            done()
        })

        it('should return one a Banner JSON string if passed a param with an _id property', (done) => {
            theObj = {
                send: (data) => {
                    console.log(data)
                }
            }
            fns.getBanner(theObj);
            done();
        })

        after((done) => {
            sandbox.restore();
            done()
        })
    })



});
...