【问题标题】:How to subscribe to Observable in a Jasmine unit test?如何在 Jasmine 单元测试中订阅 Observable?
【发布时间】:2020-09-14 10:08:48
【问题描述】:

我有一些模拟 json 数据,我想读入一些单元测试。我将其作为一个实用程序,以便其他单元测试文件可以使用它。例如:

@Injectable({providedIn: 'root'})
export class MockUtilsService {
     
    constructor(private http: HttpClient) {}

    loadData(): Observable<any[]> {
        // Read local json file for mock data
        return this.http.get<any[]>('./mock-data.json');
    }
}

然后在单元测试中:

beforeEach(async(() => {
    
    TestBed.configureTestingModule({
        providers: [MockUtilsService]
    }).compileComponents();

}));

it('retrieve data', () => {
    
    const service = TestBed.get(MockUtilsService);
    service.loadData().subscribe(data => {
        expect(data).toBeDefined();
    });

});

当我运行测试时,我看到错误:'retrieve data' has no expected.'

我不知道 loadData() 方法是否没有被调用,或者是否存在某种异步问题,即测试在调用 subscribe 方法之前完成。

【问题讨论】:

    标签: angular unit-testing jasmine


    【解决方案1】:

    你说得对,在调用 subscribe 方法之前测试就完成了。利用 Jasmine 提供的 done 回调,您可以指定测试何时完成并完成断言。

    it('retrieve data', done => { // add done as an argument here
        
        const service = TestBed.get(MockUtilsService);
        service.loadData().subscribe(data => {
            expect(data).toBeDefined();
            done(); // allow the test to come inside of this subscribe and then call done telling Jasmine you are done with your assertions.
        });
    
    });
    

    【讨论】:

      【解决方案2】:

      您正在执行异步操作,因此您需要在异步空间中运行测试。使用 fakeAsynctick 函数更新测试。

      it('retrieve data', fakeAsync(() => {
          const service = TestBed.get(MockUtilsService);
      
          service.loadData().subscribe(data => {
              expect(data).toBeDefined();
          });
          tick();
      }));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-12-27
        • 2020-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-22
        • 1970-01-01
        相关资源
        最近更新 更多