【问题标题】:Jasmine test for simple Angular2 component not working简单 Angular2 组件的 Jasmine 测试不起作用
【发布时间】:2016-11-05 15:17:50
【问题描述】:

我有这个简单的组件:

@Component({
    selector: 'messages',
    styleUrls: ['messages.component.scss'],
    templateUrl: 'messages.component.html',
})
export class MessagesComponent implements OnInit {

    constructor(private dataService: DataService) {}

    public getOne(): number{
        return 1;
    }
}

我正在尝试对其进行测试,但我无法让它工作,请帮助:

describe('Component: MessagesComponent', () => {
    let component: MessagesComponent;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [MessagesComponent],
        }).compileComponents();

        const fixture = TestBed.createComponent(MessagesComponent);
        component = fixture.componentInstance;
    });

    it('should have a defined component', () => {
        expect(true).toBeTruthy();
    });

});

(如果相关,我正在使用 webpack)

这是我得到的错误:

    Error: This test module uses the component MessagesComponent
 which is using a "templateUrl", but they were never compiled.
 Please call "TestBed.compileComponents" before your test.

【问题讨论】:

    标签: angular jasmine webpack karma-jasmine angular2-template


    【解决方案1】:

    错误:此测试模块使用了组件 MessagesComponent 这是使用“templateUrl”,但它们从未被编译过。 请在测试前调用“TestBed.compileComponents”。

    使用 Webpack 时,您不需要编译组件(使用 templateUrl)。当您使用angular2-template-loader 时,templateUrl 应该被转换为内联templates。

    请参阅 Angular 文档中的 webpack.test.js 示例。您需要确保您具有加载程序的依赖项。我想您应该已经将它用于主要项目

    "devDepdendencies": {
      "angular2-template-loader": "^0.4.0",
    }
    

    如果您仍然对我上面链接的单个配置文件感到困惑,您可能只想阅读整个Angular docs on webpack。不应该花那么长时间。但它会引导您完成主应用程序和测试的设置。

    同时查看您的previous question,您的 webpack 配置也没有任何 sass 支持。我想这是您在主应用程序 webpack 配置中配置的内容。您可以查看它以了解它是如何配置的。或者您可以查看this out。它基本上是我从 Angular 文档中整理的一个项目,只是作为一个地方所有内容的参考。 Angular 文档没有添加任何 sass 支持,但链接的项目确实添加了它。

    【讨论】:

      【解决方案2】:

      当运行时环境在测试期间编译源代码时,您会收到此测试失败消息。

      要纠正该问题,请按照以下说明调用 compileComponents()。

      beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [ YourComponent ],
        })
        .compileComponents()
        .then(() => {
          fixture = TestBed.createComponent(YourComponent);
          component = fixture.componentInstance;
        });
      }));
      

      这里我们必须用异步函数调用compileComponents(),然后在'then block'中创建一个组件实例,这样就可以解决问题了。

      请参阅https://angular.io/guide/testing#compile-components 了解更多信息。

      【讨论】:

        猜你喜欢
        • 2016-03-21
        • 2016-05-14
        • 2018-02-26
        • 2017-05-10
        • 2018-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-21
        相关资源
        最近更新 更多