[javascript] Chai : ‘should’구문으로 undefined를 테스트하는 방법

에 구축 차이가있는 AngularJS와 응용 프로그램을 테스트 튜토리얼, 나는 “해야”스타일을 사용하여 정의되지 않은 값에 대한 테스트를 추가 할. 이것은 실패합니다.

it ('cannot play outside the board', function() {
  scope.play(10).should.be.undefined;
});

“TypeError : Cannot read property ‘should’of undefined”오류가 있지만 테스트는 “expect”스타일로 통과합니다.

it ('cannot play outside the board', function() {
  chai.expect(scope.play(10)).to.be.undefined;
});

“should”로 작업하려면 어떻게해야합니까?



답변

이것은 should 구문의 단점 중 하나입니다. 모든 객체에 should 속성을 추가하여 작동하지만 반환 값이나 변수 값이 정의되지 않은 경우 속성을 보유 할 객체가 없습니다.

문서는 예를 들어 몇 가지 해결 방법을 제공합니다 :

var should = require('chai').should();
db.get(1234, function (err, doc) {
  should.not.exist(err);
  should.exist(doc);
  doc.should.be.an('object');
});


답변

should.equal(testedValue, undefined);

차이 문서에서 언급했듯이


답변

정의되지 않은 테스트

var should = require('should');
...
should(scope.play(10)).be.undefined;

null 테스트

var should = require('should');
...
should(scope.play(10)).be.null;

거짓 테스트, 즉 조건에서 거짓으로 취급

var should = require('should');
...
should(scope.play(10)).not.be.ok;


답변

(typeof scope.play(10)).should.equal('undefined');


답변

정의되지 않은 테스트에 대해 should 문을 작성하는 데 어려움을 겪었습니다. 다음은 작동하지 않습니다.

target.should.be.undefined();

다음 해결책을 찾았습니다.

(target === undefined).should.be.true()

유형 검사로도 쓸 수 있다면

(typeof target).should.be.equal('undefined');

위의 방법이 올바른지 확실하지 않지만 작동합니다.

github의 유령에서 포스트에 따르면


답변

이 시도:

it ('cannot play outside the board', function() {
   expect(scope.play(10)).to.be.undefined; // undefined
   expect(scope.play(10)).to.not.be.undefined; // or not
});


답변

@ david-norman의 대답은 문서에 따라 정확하며 설정에 몇 가지 문제가 있었고 대신 다음을 선택했습니다.

(typeof scope.play (10)). should.be.undefined;