UFO ET IT

재스민 모의 객체의 방법을 스텁하는 방법?

ufoet 2020. 11. 30. 20:25
반응형

재스민 모의 객체의 방법을 스텁하는 방법?


Jasmine 문서에 따르면 다음과 같이 mock을 만들 수 있습니다.

jasmine.createSpyObj(someObject, ['method1', 'method2', ... ]);

이 방법 중 하나를 어떻게 스텁합니까? 예를 들어 메서드가 예외를 throw 할 때 어떤 일이 발생하는지 테스트하려면 어떻게해야합니까?


당신은 체인이 method1, method2EricG은 주석으로,하지만과 andCallThrough()(또는 and.callThrough()버전 2.0). 그것은 것 실제 구현에 위임 .

이 경우 and.callFake()호출하려는 함수 와 연결 하고 전달해야합니다 (예외 또는 원하는 모든 것을 throw 할 수 있음).

var someObject = jasmine.createSpyObj('someObject', [ 'method1', 'method2' ]);
someObject.method1.and.callFake(function() {
    throw 'an-exception';
});

그런 다음 다음을 확인할 수 있습니다.

expect(yourFncCallingMethod1).toThrow('an-exception');

Typescript를 사용하는 경우 메서드를 Jasmine.Spy. 위의 답변에서 (이상하게도 의견에 대한 담당자가 없습니다) :

(someObject.method1 as Jasmine.Spy).and.callFake(function() {
  throw 'an-exception';
});

내가 과잉 엔지니어링인지 모르겠어요. 지식이 부족해서 ...

Typescript의 경우 다음을 원합니다.

  • 기본 유형의 Intellisense
  • 함수에서 사용되는 방법 만 모의하는 기능

유용한 정보를 찾았습니다.

namespace Services {
    class LogService {
        info(message: string, ...optionalParams: any[]) {
            if (optionalParams && optionalParams.length > 0) {
                console.log(message, optionalParams);
                return;
            }

            console.log(message);
        }
    }
}

class ExampleSystemUnderTest {
    constructor(private log: Services.LogService) {
    }

    doIt() {
        this.log.info('done');
    }
}

// I export this in a common test file 
// with other utils that all tests import
const asSpy = f => <jasmine.Spy>f;

describe('SomeTest', () => {
    let log: Services.LogService;
    let sut: ExampleSystemUnderTest;

    // ARRANGE
    beforeEach(() => {
        log = jasmine.createSpyObj('log', ['info', 'error']);
        sut = new ExampleSystemUnderTest(log);
    });

    it('should do', () => {
        // ACT
        sut.doIt();

        // ASSERT
        expect(asSpy(log.error)).not.toHaveBeenCalled();
        expect(asSpy(log.info)).toHaveBeenCalledTimes(1);
        expect(asSpy(log.info).calls.allArgs()).toEqual([
            ['done']
        ]);
    });
});

@Eric Swanson의 답변을 기반으로 테스트에서 사용하기 위해 더 읽기 쉽고 문서화 된 기능을 만들었습니다. 또한 매개 변수를 함수로 입력하여 유형 안전성을 추가했습니다.

이 코드를 필요한 모든 테스트 파일에서 가져올 수 있도록 공통 테스트 클래스 어딘가에 배치하는 것이 좋습니다.

/**
 * Transforms the given method into a jasmine spy so that jasmine functions
 * can be called on this method without Typescript throwing an error
 *
 * @example
 * `asSpy(translator.getDefaultLang).and.returnValue(null);`
 * is equal to
 * `(translator.getDefaultLang as jasmine.Spy).and.returnValue(null);`
 *
 * This function will be mostly used in combination with `jasmine.createSpyObj`, when you want
 * to add custom behavior to a by jasmine created method
 * @example
 * `const translator: TranslateService = jasmine.createSpyObj('TranslateService', ['getDefaultLang'])
 * asSpy(translator.getDefaultLang).and.returnValue(null);`
 *
 * @param {() => any} method - The method that should be types as a jasmine Spy
 * @returns {jasmine.Spy} - The newly typed method
 */
export function asSpy(method: () => any): jasmine.Spy {
  return method as jasmine.Spy;
}

사용법은 다음과 같습니다.

import {asSpy} from "location/to/the/method";

const translator: TranslateService = jasmine.createSpyObj('TranslateService', ['getDefaultLang']);
asSpy(translator.getDefaultLang).and.returnValue(null);

참고 URL : https://stackoverflow.com/questions/13642884/how-to-stub-a-method-of-jasmine-mock-object

반응형