【问题标题】:Pass data from one it block to another将数据从它阻塞的一个传递到另一个
【发布时间】:2021-03-02 09:45:12
【问题描述】:

如上图所示,在第一个 it 块中分配的控制器值在第二个 it 块中不再相同。这是默认行为吗?我们可以在 karma 配置文件中做一些更改来解决这个问题吗?

本项目基于 angularjs 1.7.9,使用 karma 和 jasmine。

【问题讨论】:

    标签: javascript angularjs unit-testing jasmine karma-jasmine


    【解决方案1】:

    我认为你可以利用beforeEach

    describe('Login', function () {
      beforeEach(() => {
        $controller.name = 'Pankaj';
      });
    
      it('test one', function () {
        console.log($controller.name);
      });
       
      it('test two', function () {
        console.log($controller.name);
      });
    });
    

    beforeEach 在每个 it 块之前运行。

    编辑

    您必须正确使用describe, beforeEach, beforeAll, afterEach, and afterAlldescribe 您可以按功能/情况进行拆分,beforeEach 在每个 it 之前运行,beforeAlldescribe 块中运行一次,afterEachdescribe 块中的每个 it 之后运行,以及afterAll 在所有 it 块在 desribe 块中完成后运行一次。

    describe('Login', function () {
      beforeEach(() => {
        $controller.name = 'Pankaj';
      });
    
      it('test one', function () {
        console.log($controller.name);
      });
    
      it('test two', function () {
        console.log($controller.name);
      });
      describe('dynamic part', function () {
        beforeEach(() => {
          // call the function that will change the variable
        });
        it('test 1', function () {
          // your assertions
        });
        it('test 2', function () {
          // your assertions
        });
      });
    });
    

    【讨论】:

    • 代码的动态部分呢?如果我从第一个块中调用一个初始化某个变量的函数然后必须在第二个块中使用相同的变量怎么办?
    • 但是将该函数调用放在 beforeEach 中会增加单元测试的负载。就没有别的办法了吗?
    • 我认为这将是最小的。我想不出别的办法了。
    猜你喜欢
    • 2021-07-19
    • 1970-01-01
    • 2017-04-16
    • 2018-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多