如何解决“错误:无法从同步测试中调用setTimeout。”在测试服务时?

时间:2019-06-30 08:23:32

标签: unit-testing jasmine angular7 angular-services

我正在尝试使用Jasmine + Karma对使用ngx-socket-io的非常基本的服务进行单元测试。

我不断收到public class Jon: Person { public static var shared: Jon = Jon() required init() {} }

这是我的服务

Error: Cannot call setTimeout from within a sync test.

这是我的单元测试:

import { Injectable } from '@angular/core';
import { Socket } from 'ngx-socket-io';
import { Message } from 'src/app/models/message';

@Injectable({
  providedIn: 'root'
})
export class MessageService {

  constructor(private socket: Socket) { };

  newMessages(){
    return this.socket.fromEvent<Message>('newMessage');
  }

  newMessage(message: String) {
    this.socket.emit('messageSent', message);
  }
}

这是完整的错误输出:

import { TestBed } from '@angular/core/testing';
import { MessageService } from './message.service';
import SocketMock from 'socket.io-mock';
import { WrappedSocket } from 'ngx-socket-io/src/socket-io.service';

describe('MessageService', () => {
  let service: MessageService;
  let socket: WrappedSocket = new WrappedSocket(new SocketMock());
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers :[
        MessageService,
        {provide: WrappedSocket, useValue: socket}
      ]
    });
    service = TestBed.get(MessageService);
  });

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

我只想测试该服务是否已创建。怎么回事,我如何才能通过测试?

2 个答案:

答案 0 :(得分:0)

尝试在每个之前使用异步。可能是从那里调用setTimeout的。

答案 1 :(得分:0)

检查您的test.ts文件。主要是zone.js导入 订单应为

import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/proxy';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/jasmine-patch';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';

参考-https://github.com/angular/zone.js/issues/1058