这是集成测试解决方案,为了存根链方法,您需要使用stub.returnsThis();
例如
server.ts
:
import express from 'express';
import categories from './model';
import http from 'http';
const app = express();
app.get('/api/things',async (req,res) => {
const items = await categories
.find({ name: 'book' })
.limit(10)
.skip(0);
res.json(items);
});
const server = http.createServer(app).listen(3000,() => {
console.info('Http server is listening on http://localhost:3000');
});
export { server };
model.ts
:
import { model,Schema } from 'mongoose';
const modelName = 'category';
const categorySchema = new Schema(
{
name: String,parent: { type: Schema.Types.ObjectId,ref: modelName },slug: { type: String },ancestors: [{ _id: { type: Schema.Types.ObjectId,name: String,slug: String }],},{
collection: 'category-hierarchy_categories',);
const categories = model(modelName,categorySchema);
export default categories;
server.integration.spec.ts
:
import request from 'supertest';
import { server } from './server';
import { expect } from 'chai';
import sinon from 'sinon';
import categories from './model';
after((done) => {
server.close(done);
});
describe('Thing API',() => {
it('returns some things',(done) => {
const limitStub = sinon.stub().returnsThis();
const skipStub = sinon.stub().returns([{ foo: 'bar' }]);
sinon.stub(categories,'find').callsFake((): any => {
return {
limit: limitStub,skip: skipStub,};
});
request(server)
.get('/api/things')
.expect((res) => {
expect(res.body).to.be.an('array');
expect((categories.find as sinon.SinonStub).calledWith({ name: 'book' })).to.be.true;
expect(limitStub.calledWith(10)).to.be.true;
expect(skipStub.calledWith(0)).to.be.true;
})
.expect(200,done);
});
});
覆盖率100%的集成测试结果:
Http server is listening on http://localhost:3000
Thing API
✓ returns some things
1 passing (43ms)
----------------------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------------------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
model.ts | 100 | 100 | 100 | 100 | |
server.integration.spec.ts | 100 | 100 | 100 | 100 | |
server.ts | 100 | 100 | 100 | 100 | |
----------------------------|----------|----------|----------|----------|-------------------|
源代码:https://github.com/mrdulin/mongoose5.x-lab/tree/master/src/stackoverflow/58787092
本文链接:https://www.f2er.com/3129890.html