垫小吃店单元测试消息为空 [英] mat snackbar unit test message is null

查看:31
本文介绍了垫小吃店单元测试消息为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义服务,它使用 matSnackbar 来显示警报,还有一个自定义 matSnackbar 组件用作snackBar 的模板.我为它编写了一个单元测试,并想测试在其中显示我的消息:

i have a custom service that uses matSnackbar to show the alerts, and a custom matSnackbar component to use as template for snackBar. i wrote a unit test for it and want to test the showing my message in it:

fit('should show my alert message',  () => {
    service.openSnackBarFromComponent('lia lia');
    expect(element.querySelector('.message-container span').innerText).toBe('lia lia');
  });

我在浏览器中看到它显示了我的消息 "lia lia" 但在上面的测试中 .message-container span 的内容为空.我的问题是为什么它显示 null 或任何其他方式来测试我的消息?

i see in browser that it shows my message "lia lia" but in the test above content of the .message-container span in null. my qusetion is why it shows null and or any another way to test my message?

推荐答案

按照我的评论,fixture.detectChanges 应该可以解决您的问题.

Following my comment, fixture.detectChanges should resolve your issue.

至于单元测试:您一定已经猜到了,单元测试意味着测试一个单元.

As for unit testing : as you must have guessed, unit testing means testing a unit.

一个单元就是一段代码

  • 你自己写的
  • 在给定范围(函数、类)中定义的
  • 具有依赖项(注入、参数...)

当你测试那个单元时,你有几个步骤要尊重

When you test that unit, you have several steps to respect

  • 模拟依赖
  • 隔离设备
  • 测试副作用

单元测试的目的是防止修改带来的副作用.

例如,您有一个组件,如果 HTTP 响应为 200,它会简单地将按钮涂成绿色.

For instance, you have a component that simply colors a button in green if the HTTP answer is 200.

单元测试的目的是确保如果答案是 200,颜色会变成绿色.

The unit test purpose is to ensure that the color becomes green if the answer is 200.

这意味着如果你没有收到 200,颜色应该不会改变,如果你收到 200,颜色应该只是绿色.

This means that if you don't receive 200, the colour should not change, and if you receive 200, the colour should be green only.

适用于您的案例,您的测试目的是确保使用您的自定义组件调用小吃店.

Applied to your case, the purpose of your test would be to ensure that the snacker is called with your custom component.

您的目的不是测试小吃店的工作.小吃店本身就是一个单元,您没有编写代码:小吃店的单元测试由 Angular Material 单元测试进行测试,而不是您.

It's not your purpose to test the snackar works. The snackbar is a unit itself, and one you did not code : the unit testing of the snackbar is tested by the Angular Material unit tests, not you.

好吧,您的测试没有错:它只是另一个测试的副本,因此从它已经过测试的意义上说,它是无用的".

In fine, your test isn't wrong : it's just a duplicate of another test, so it's "useless" in the sense that it has already been tested.

如果你继续这样测试,你将花费测试时间的 3 到 4 倍,这最终不会有成效.

If you continue to test like that, you will spend 3, 4 times the time you would have spent testing, which isn't productive in the end.

这篇关于垫小吃店单元测试消息为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆