Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
127 changes: 91 additions & 36 deletions test/unit/controllers/Consultor.js
Original file line number Diff line number Diff line change
@@ -1,51 +1,106 @@
var chai = require('chai'),
chaiAsPromised = require('chai-as-promised'),
assert = chai.assert,
path = require('path');
chaiAsPromised = require('chai-as-promised');

chai.use(chaiAsPromised);

var appDir = path.resolve(__dirname, '../../../common.blocks/app'),
models = require(path.join(appDir, 'models')),
Consultor = require(path.join(appDir, 'controllers/Consultor'));
var assert = chai.assert,
_ = require('lodash'),
path = require('path'),
vow = require('vow');

describe('Controller: Consultor', function () {
var appDir = './common.blocks/app/',
models = require(path.resolve(appDir + 'models/')),
Consultor = require(path.resolve(appDir + 'controllers/Consultor'));
User = require(path.resolve(appDir + 'controllers/User'));

var consultorModel;
models(function (err, db) {
if (err) throw err;

before(function() {
return new Promise((resolve, reject) => {
models(function (err, db) {
if (err) throw reject(err);
db.sync(function (err) {
if (err) throw err;

db.sync(function (err) {
if (err) throw reject(err);
resolve(db.models['s-consultor']);
});
var VK_USER_ID = 100,
usersModel = db.models['users'],
consultorModel = db.models['s-consultor'];

});
}).then((model) => consultorModel = model);
});
describe('Controller: Consultor', function () {

beforeEach(function() {
return new Promise((resolve, reject) => {
consultorModel.find().remove(function(err) {
if (err) {
reject(err);
}
resolve();
before(function (done) {
this.timeout(10000);
User.deleteByVKId(usersModel, VK_USER_ID).then(function () {
done();

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

куда делся код на new Promise ? верните

});
});
beforeEach(function (done) {
this.timeout(10000);
consultorModel.find().remove(function () {
done();
});
});
});
});

describe('create', function() {
it('should create question', function () {
var question = 'What\'s up?',
userId = 'a12345678901';
describe('Create consultor', function () {
it('should create consultor', function () {
var defered = vow.defer(),

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

нужно было объединить два файла, а не удалить то что было и добавить своё.

ребейзить конфликты так же будете?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Наверно нужно было об этом что то написать, я для этого специально сделал отдельный тест в отдельной ветке, чтобы не перетирать чужие изменения - тестовое задание.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

просто все затянулось... я думал все пройдет быстрее и конфликтов не будет
просто учитывайте, что это все в проект вмержится, если до ума доведем

question = 'Test question one',
userId = 'a12345678901';

return Consultor
.create(consultorModel, question, userId)
.then((data) => assert.equal(data.question, question));
Consultor.create(consultorModel, question, userId)
.then(function (data) {
defered.resolve(data);
});

return assert.isFulfilled(
defered.promise(),
'Should be resolved'
);
});

it('should get all questions', function () {
var defered = vow.defer(),
question = 'Test question two';

User.createByVKId(usersModel, VK_USER_ID)
.then(function () {
User.getByVKId(usersModel, VK_USER_ID)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

нам не нужно создавать нового пользователя, можно подставить любой произвольный id, userId = 'a12345678901' например

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

возможно, мне нужно перепроверить, но по моему там вопросы выбираются по реальным user_id

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

в тестовых данных нет ничего реального, тут все изолировано надо проверять

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

я могу ошибаться, но если на вход дать фейковый id юзера, то мы не получим вопросов, выборка идёт с учётом id юзера(из users)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

да, точно. Это Consultor.getAllQuestions криво написан, что завязан на пользователей :(
вопрос снимается, надо будет порефакторить.

.then(function (data) {
defered.resolve(data);

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

два резолва у одно и того же промиса быть не может, уберите этот

и deferred пишется с двумя r

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

возможно моё решение не совсем правильно, я предполагал, на резолв первого промиса получить user_id, а на резолв второго промиса получить массив вопросов

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

и что потом с ним происходит? ассерт ведь один

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ассерт проверяет количество вопросов - цель теста, я знаю, что создаю один вопрос, и убеждаюсь, что их действительно один, а не два или три.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ок, тогда зачем конкретно в этой строке: defered.resolve(data); ??? в data ведь массив из одного пользователя, полученного в getByVKId. Какое вообще это имеет отношение к тесту?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

я получаю id созданного пользователя, при создании пользователя я в ответ не получаю id пользователя. Потом использую в тесте id этого пользователя(создаю вопрос), потому как выборка вопросов идёт с учётом id пользователя, если я на вход тесту дам фейковый id, то не получу массив вопросов.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

что делает defered.resolve(data); ?

Consultor.create(consultorModel, question, data[0]._id)
.then(function () {
Consultor.getAllQuestions(db)
.then(function(questions) {
defered.resolve(questions.length);
});
});
});
});

return assert.eventually.lengthOf(
defered.promise(),
1,
'Should be equal 1'
);
});

it('should find consultor by id', function () {
var defered = vow.defer(),
question = 'Test question three',
userId = 'a12345678901';

Consultor.create(consultorModel, question, userId)
.then(function (data) {
Consultor.getById(consultorModel, data._id)
.then(function (question) {
defered.resolve(!_.isEmpty(question));
});
});

return assert.eventually.ok(
defered.promise(),
'Should be not empty'
);
});
});
});
run();
});
});
});