Кажется, я не могу правильно смоделировать импорт в моем файле spe c, и мне интересно, может ли кто-нибудь увидеть, что мне не хватает.
Вот экспортированный класс для моего подключения к базе данных
import Knex from 'knex';
import { merge } from 'lodash';
import knexfile from '../knexfile';
class Database {
private knexInstance: Knex;
private config: object;
connect(options = {}): void {
if (this.knexInstance) {
return;
}
this.config = merge({}, knexfile, options);
this.knexInstance = Knex(this.config);
}
get query(): Knex {
if (!this.knexInstance) {
this.connect();
}
return this.knexInstance;
}
close(done): void {
if (!this.knexInstance) {
done();
return;
}
this.knexInstance.destroy(done);
}
}
export default new Database();
Вот файл действий, который пытается использовать файл базы данных.
import db from '../../database';
const tableName = 'attempts';
export const typeDef = `
extend type Query {
attempt(id: String): Attempt!
}
extend type Mutation {
createAttempt(questionId: String!, attemptId: String!, choiceId: String): Attempt
}
type Attempt {
id: String!
correctanswers: Int!
userid: String!
examid: String!
}
`;
export const resolvers = {
Query: {
attempt(_, { id = '' }) {
return db
.query(tableName)
.where({ id })
.first();
},
},
Mutation: {
async createAttempt(root, args) {
const [answer] = await db
.query(tableName)
.insert(args)
.returning('*');
return answer;
},
},
};
А вот мой тестовый файл.
import { createSandbox } from 'sinon';
import { resolvers } from './answer';
import db from '../../database';
import * as should from 'should';
const sandbox = createSandbox();
describe('Answer', () => {
afterEach(() => sandbox.restore());
describe('Query Answer', () => {
it('should return answer by id', async () => {
const expected = { id: 'xxx' };
const firstSpy = sandbox.fake.resolves(expected);
const whereSpy = sandbox.fake.resolves({
first: firstSpy,
});
// This stub never seems to get called. It doesn't look like the import is ever being replaced with the stub in the implementation file.
const querySpy = sandbox.stub(db, 'query').callsFake(() => {
return Promise.resolve({
where: whereSpy,
});
});
const inputId = '100';
const result = await resolvers.Query.answer(null, { id: inputId });
sandbox.assert.calledOnce(querySpy);
sandbox.assert.calledOnce(whereSpy);
sandbox.assert.calledOnce(firstSpy);
result.should.deepEqual(expected);
});
});
});
Когда я запускаю проверяет, не похоже ли это, что импорт когда-либо заменяется заглушкой в файле реализации, и я не понимаю, почему.