首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何模拟对象并验证给定参数是否已提供给此模拟

如何模拟对象并验证给定参数是否已提供给此模拟
EN

Stack Overflow用户
提问于 2022-05-09 15:07:51
回答 1查看 354关注 0票数 1

我正试图在HttpInterceptor的帮助下测试ng-mocks

代码语言:javascript
复制
    @Injectable()
    export class AuthTokenInterceptor implements HttpInterceptor {
      constructor(private store: Store) {}
    
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const currentToken = this.store.selectSnapshot(state => state.accounts.accessToken);
    
        if (currentToken) {
          req = req.clone({
            setHeaders: { Authorization: `Bearer ${currentToken}` },
          });
        }
        return next.handle(req);
      }
    }

我很难了解如何提供next参数,特别是因为我想检查对象是否存在setHeaders属性(或不存在):

代码语言:javascript
复制
    describe('Unauth guard test', () => {
      beforeEach(() => {
        return MockBuilder(AuthTokenInterceptor, AppModule).mock(Store);
      });
    
      it('should allow access if not authenticated', () => {
        //Arrange
        const fakeToken = 'fakeToken';
        const storeDispatchSpy = MockInstance(Store, 'selectSnapshot', jasmine.createSpy().and.returnValue(fakeToken));
        const httpHandlerSpy = MockInstance(HttpHandler, 'handle', jasmine.createSpy().and.returnValue(fakeToken));
        const fixture = MockRender(AuthTokenInterceptor);
        const interceptor = fixture.point.componentInstance;
       const request = new HttpRequest('GET', 'http://localhost:4200/');
    
        //Act
        const result = interceptor.intercept(request, httpHandlerSpy.???);//How to provide a mock of HttpHandler?
    
        //Assert
        expect(storeDispatchSpy).toHaveBeenCalled();
        expect(httpHandlerSpy).toHaveBeenCalledOnceWith(???);//How to verify that one parameter of the HttpRequest is set to specific value?
      });
    });

但是如何向拦截方法提供模拟实例呢?更复杂的是,如何检查我的间谍是否被一个具有特定价值的对象调用?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-09 17:23:31

在您的情况下,您需要提供mockStore +将拦截器与其他拦截器隔离开来。

一个来自ng-mocks docs and http interceptors的例子。

https://codesandbox.io/s/intelligent-stallman-9bwup0?file=/src/test.spec.ts

代码语言:javascript
复制
describe('AuthTokenInterceptor', () => {
  beforeEach(() => {
    return (
      MockBuilder(AuthTokenInterceptor, AppModule)
        // required for interceptors
        .exclude(NG_MOCKS_INTERCEPTORS)
        .keep(HTTP_INTERCEPTORS)

        .replace(HttpClientModule, HttpClientTestingModule)
    );
  });

  it('adds header', () => {
    // creating an empty fixture
    const fixture = MockRender('', null, false);

    // stubbing store
    const store = ngMocks.findInstance(Store);
    ngMocks.stubMember(store, 'selectSnapshot', callback =>
      callback({
        accounts: {
          accessToken: 'Testing',
        },
      }),
    );

    // render
    fixture.detectChanges();

    // instances to test how HttpClient uses interceptors
    const client = ngMocks.findInstance(HttpClient);
    const httpMock = ngMocks.findInstance(HttpTestingController);

    // Let's do a simple request.
    client.get('/target').subscribe();

    // Now we can assert that a header has been added to the request.
    const req = httpMock.expectOne('/target');
    req.flush('');
    httpMock.verify();

    // asserting headers
    expect(req.request.headers.get('Authorization')).toEqual(
      'Bearer Testing',
    );
  });
});
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72174210

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档