You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jasmine测试中Mock NGRX工厂选择器

测试使用NGRX工厂选择器的组件

以下是两种Mock工厂选择器并完成组件测试的实用方案:

方案一:使用MockStore覆盖选择器返回值

利用@ngrx/store/testing提供的MockStore和overrideSelector方法,直接指定目标工厂选择器的返回结果:

1. 配置测试环境

import { MockStore, provideMockStore } from '@ngrx/store/testing';
import { CustomerComponent } from './customer.component';
import { selectCustomer } from './customer.selector';
import { of } from 'rxjs';

describe('CustomerComponent', () => {
  let store: MockStore;
  let component: CustomerComponent;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [CustomerComponent],
      providers: [
        // 初始化空的初始状态,后续可按需覆盖
        provideMockStore({ initialState: { customers: {} } })
      ]
    }).compileComponents();

    store = TestBed.inject(MockStore);
    component = TestBed.createComponent(CustomerComponent).componentInstance;
  });

2. 编写测试用例

it('should select the target customer via factory selector', () => {
    // 定义模拟的客户数据
    const mockCustomer = { id: '3', name: 'John Doe' };
    
    // 针对传入id='3'的工厂选择器,覆盖其返回值
    store.overrideSelector(selectCustomer('3'), mockCustomer);
    // 刷新Store状态,确保组件能获取到最新值
    store.refreshState();

    // 订阅组件中的data流,验证结果
    component.data.subscribe(customer => {
      expect(customer).toEqual(mockCustomer);
    });
  });
});

方案二:Spy拦截Store的select调用

通过Jasmine Spy直接拦截store.select方法,匹配目标选择器后返回模拟数据:

it('should fetch correct customer via spied store select', () => {
  const mockCustomer = { id: '3', name: 'Jane Smith' };
  
  // Spy on store.select,匹配目标选择器时返回模拟Observable
  spyOn(store, 'select').and.callFake((selector) => {
    if (selector === selectCustomer('3')) {
      return of(mockCustomer);
    }
    return of(null);
  });

  // 重新初始化组件,确保Spy生效
  component = TestBed.createComponent(CustomerComponent).componentInstance;

  component.data.subscribe(customer => {
    expect(customer).toEqual(mockCustomer);
  });
});

注意事项

  • 注意参数类型匹配:你的组件中传入的是数字3,但选择器定义的参数是string类型,测试时要统一为字符串'3'避免类型错误。
  • 如果组件在ngOnInit中调用store.select,需确保在设置Mock/Spy之后再触发ngOnInit(比如调用component.ngOnInit())。

内容的提问来源于stack exchange,提问作者Satyam Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 05:12:49