垫快餐栏单元测试消息为空 [英] mat snackbar unit test message is null

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

问题描述

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

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的内容为空.我的qusetion是为什么它显示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.

关于单元测试:正如您已经猜到的那样, unit 测试意味着测试一个单元.

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

单位是一段代码

  • 你写了自己
  • 在给定范围(函数,类)中定义的
  • 具有依赖性(注入,参数...)
  • that you wrote yourself
  • that is defined in a given scope (function, class)
  • that has dependencies (injection, parameters ...)

测试该单元时,您需要遵循几个步骤

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天全站免登陆