如何存根茉莉花模拟对象的方法?

Ade*_*lin 66 javascript jasmine

根据Jasmine文档,可以像这样创建一个模拟:

jasmine.createSpyObj(someObject, ['method1', 'method2', ... ]);
Run Code Online (Sandbox Code Playgroud)

你如何存根这些方法之一?例如,如果要测试方法抛出异常时会发生什么,那么您将如何做?

zby*_*our 104

正如EricG评论的那样,你必须链接method1,method2但不能andCallThrough()(或and.callThrough()在版本2.0中).它将委托真正的实施.

在这种情况下,您需要链接and.callFake()并传递您想要调用的函数(可以抛出异常或任何您想要的东西):

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

然后你可以验证:

expect(yourFncCallingMethod1).toThrow('an-exception');
Run Code Online (Sandbox Code Playgroud)

  • Jasmine 2.0将语法改为`.and.callFake()`,`.and.callThrough()`,`.and.returnValue()`http://jasmine.github.io/2.0/introduction.html#section -Spies (6认同)

Eri*_*son 18

如果您使用的是Typescript,那么将方法强制转换为有用Jasmine.Spy.在上面的答案中(奇怪的是我没有代表评论):

(someObject.method1 as Jasmine.Spy).and.callFake(function() {
  throw 'an-exception';
});
Run Code Online (Sandbox Code Playgroud)

我不知道我是否过度工程,因为我缺乏知识......

对于Typescript,我想要:

  • 来自底层类型的智能感知
  • 能够模拟函数中使用的方法

我发现这很有用:

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']
        ]);
    });
});
Run Code Online (Sandbox Code Playgroud)


小智 9

角 9

jasmine.createSpyObj在测试注入简单服务的组件时,使用是理想的。例如:假设,在我的 HomeComponent 中,我有一个 HomeService(注入)。HomeService 中唯一的方法是getAddress()。创建 HomeComponent 测试套件时,我可以将组件和服务初始化为:

describe('Home Component', () => {
    let component: HomeComponent;
    let fixture: ComponentFixture<HomeComponent>;
    let element: DebugElement;
    let homeServiceSpy: any;
    let homeService: any;

    beforeEach(async(() => {
        homeServiceSpy = jasmine.createSpyObj('HomeService', ['getAddress']);

        TestBed.configureTestingModule({
           declarations: [HomeComponent],
           providers: [{ provide: HomeService, useValue: homeServiceSpy }]
        })
        .compileComponents()
        .then(() => {
            fixture = TestBed.createComponent(HomeComponent);
            component = fixture.componentInstance;
            element = fixture.debugElement;
            homeService = TestBed.get(HomeService);
            fixture.detectChanges();
        });
    }));

    it('should be created', () => {
        expect(component).toBeTruthy();
    });

    it("should display home address", () => { 
        homeService.getAddress.and.returnValue(of('1221 Hub Street'));
        fixture.detectChanges();

        const address = element.queryAll(By.css(".address"));

        expect(address[0].nativeNode.innerText).toEqual('1221 Hub Street');
    });
 });
Run Code Online (Sandbox Code Playgroud)

这是使用jasmine.createSpyObj. 但是,如果您的服务有更多方法更复杂的逻辑,我会建议创建一个 mockService 而不是 createSpyObj。例如: providers: [{ provide: HomeService, useValue: MockHomeService }]

希望这可以帮助!