如何对未在文件中声明的对象的实例进行存根
对不起,我对单元测试有点陌生,所以不确定这是否会非常明显,我目前在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();
})
})
});
任何帮助解决此问题的人,将不胜感激!
回答如下:感谢@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()
})
})
});