Интеграционный тест Nodejs не сохраняет или не возвращает данные

Приведенный ниже код, кажется, никогда не завершается при использовании в скрипте интеграционного теста Данные поступают на сервер так же, как и успешные запросы почтальона, но затем сохранение никогда не выполняется, и я действительно пытаюсь понять, почему.

Мой инстинкт говорит, что это асинхронный код, и поэтому мне нужно отложить ожидание, пока сохранение не разрешится, я пробовал это, но я не уверен, что сделал это правильно, и это не сработало!! Каждый раз, когда я запускаю код, у него заканчивается время, я устанавливал таймаут на 10000.

Тот же самый код работает, когда используется в почтальоне! Пожалуйста, пожалуйста, кто-нибудь может дать мне некоторое представление о том, что здесь происходит, почему мои тесты не выполняются, но мой почтовый ящик и что я могу с этим сделать.

tempUser.js

// create a new user based on the form submission
exports.create = function(request, response) {
    const params = request.body;
    console.log(params);
    // Create a new user based on form parameters
    const tempUser = new TempUser({
      phone: params.cellphone,
      countryCode: params.country_code,
      email: params.email
    });

    console.log(`create temp:${tempUser}`);

    tempUser.save(function(err, doc) {
        if (err) {
          console.log(doc);
          response.send(err);
        } else {
            // If the user is created successfully, send them an account
            // verification token
            tempUser.sendAuthyToken(function(err) {
                if (err) {
                    console.log("err");
                    response.send(err);
                }
            });
        response.send(doc);
      }
    });
};

Терминал

> NODE_ENV=test PORT=3001 mocha --timeout 10000 tests/**/*.test.js


    1) should create a new tempUser


  0 passing (10s)
  1 failing

  1) Post /tempUser
       should create a new tempUser:
     Error: Timeout of 10000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.




TypeError: Cannot read property 'status' of undefined
    at Test._assertStatus (/Users/hcbh96/Desktop/PhonexDevelopment/Phonex/node_modules/supertest/lib/test.js:263:11)
    at Test._assertFunction (/Users/hcbh96/Desktop/PhonexDevelopment/Phonex/node_modules/supertest/lib/test.js:281:11)
    at Test.assert (/Users/hcbh96/Desktop/PhonexDevelopment/Phonex/node_modules/supertest/lib/test.js:171:18)
    at Server.assert (/Users/hcbh96/Desktop/PhonexDevelopment/Phonex/node_modules/supertest/lib/test.js:131:12)
    at Object.onceWrapper (events.js:313:30)
    at emitNone (events.js:106:13)
    at Server.emit (events.js:208:7)
    at emitCloseNT (net.js:1655:8)
    at _combinedTickCallback (internal/process/next_tick.js:135:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)
undefined

Тестовый файл

describe("Post /tempUser", function(){

  it('should create a new tempUser', async function(done){
    var userEmail = 'test@test.com';
    var userPhone = '5005550006';
    var userCountryCode = '1';

    request(app)
    .post('/api/users/temp-user/create')
    .send({cellphone:userPhone,country_code:userCountryCode,email:userEmail})
    .expect(200)

    .end(function(err,res){
      console.log(err);
      console.log(res);
      if(err){
        return done(err);
      };

      TempUser.find().then((tempUsers)=>{
        expect(tempUsers.length).toBe(1);
        expect(tempUsers[0].countryCode).toBe(userCountryCode);
        expect(tempUsers[0].email).toBe(userEmail);
        expect(tempUsers[0].phone).toBe(userPhone);
        done();
      }).catch((e)=>done(e));
    });
  });
});

Спасибо заранее за любую помощь

0 ответов

Другие вопросы по тегам